shubham jha shubham jha - 2 months ago 10
HTML Question

jQuery adding blank option field in the select box

I have the following jquery code that is working for two select fields.

$(document).ready(function () {
$("#select1").change(function(){
$('#trblock').fadeIn();
if ($(this).data('options') == undefined) {
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
});


However I want the second select box having id="select2" to be loaded with 1 extra blank option at the top. I tried simply adding the HTML part but I think that due to the jQuery code effect above its not allowing it. So I think modifying the jQuery part instead will do the task. But I have a newbie to jQuery. Please help me how to get it.

Something like this in HTML.

<select name="" id="select2">
<option value=""></option> // I want this here (by changing/adding codes in jquery)
<option value="1" date="01">Value 1</option>
<option value="2" date="02">Value 2</option>
<option value="3" date="03">Value 3</option>
<option value="4" date="04">Value 4</option>
<option value="5" date="05">Value 5</option>
</select>

Answer

First create the empty option, then add the rest with .append()

$(document).ready(function () {
    $("#select1").change(function(){
      $('#trblock').fadeIn();
      if ($(this).data('options') == undefined) {
        $(this).data('options', $('#select2 option').clone());
      }
      var id = $(this).val();
      var options = $(this).data('options').filter('[value=' + id + ']');
      $('#select2').html('<option value="">').append(options);
    });
});    
Comments