besmart besmart - 2 months ago 6
Javascript Question

Trying to add a blank <option> with jQuery from a dropdown with ajax

I have a JS function which populates a select based on the value of a first select, but i would like to add an empty at the beginning.

this is the function

function createParkFloorMenu(){
$('#idPark').on('change',function(event) {
var parks = $(this).val();

$.get(floorListUrl, {
idPark: parks
}, function(response) {

var select = $('#idPiano');

select.find('option').remove();

$.each(response, function(i, v) {
$('<option>').val(v.idPiano).text(v.nomePiano).appendTo(select);

});
});

});
}


I tried to add

$('option').val('').text('Seleziona Piano').appendTo($('#idPiano'));


with no success because it populates all the dropdown in my form with "Seleziona Piano" options...

Answer

$('option') will find the <option> tags in your dom. If you want to create a new option tag - you need to use $('<option>') (like you already have in your code).

You can use:

 $('<option>').val('').text('').appendTo(select);

in your code right after the remove() part.