skip to Main Content

In my project, I’m using laravel as a backend. My case is, when the relevant page is loaded it sends an ajax request to get vehicle data, the vehicle has vehicle model & plate number properties. I want ajax response values show in a select field. I’m using jquery ajax to do this, but it does not append the values to the select field. There is no problem in the success response. how can append these values to a select options?

My HTML :

<div class="raw">
    <div class="form-group row" style="justify-content:center">
        <div class="col-sm-6">
            <label for="vehicleinfo">Select a Vehicle</label>
            <select class="custom-select form-control" id="select_list">         
                <option>- Select a Vehicle -</option>
            </select>
        </div>
    </div>
</div>

My JS:

//?show vehicles
$(document).ready(function(){
	$.ajax({
		type: "GET",
		url: '/get_vehicles',
	})
	.done(function(res) {
		$.each(res, function(index, value) {
			$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>');
			
			let select_option = '';
			select_option += "<option value='"+ value.vehiclemodel +"'>"+ value.platenumber +"</option>"; 
			$('#selecet_list').append(select_option);
		});
	})
	.fail(function(err) {
		console.log(err);
	});
});

$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>'); This code part is working and successfully append values to the div element. somehow it does not work for the select field.

Appreciate your help. thank you.

2

Answers


  1. In order to add <option>s to your existing <select>, you can do it with one of these approaches:

    Jquery standard fashion

    $.each(res, function (index, value) {
      $('#select_list').append($('<option/>', { 
          value: index,
          text : value 
      }));
    });
    

    Jquery and pure js combination

    $.each(res, function (index, value) {
      $("#select_list").append(new Option("option text", "value"));
    });
    
    Login or Signup to reply.
  2. You have defined id of element in HTML as select_list.

    But you are using id named selecet_list in your jQuery script.

    That’s an issue need to be resolved.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search