Adam Levitt
Adam Levitt

Reputation: 10476

jQuery IE9 repopulating select options with ajax

The following code works perfectly in non-IE browsers. Please note that these first three options were added via jQuery.

<select id="mySelect" name="mySelect">
  <option value="1">MyVal1</option>
  <option value="2">MyVal2</option>
  <option value="3">MyVal3</option>
</select>

I clear out the options so I can add new ones:

// my new values has the proper values of [{"Id": 4, "Text" : "MyVal4"}, {"Id": 5, "Text": "MyVal5"}]
$("#mySelect").empty();
for (var i = 0; i < myNewVals.length; i++) {            
  $("#mySelect").append('<option value="' + myNewVals[i].Id + '">' + myNewVals[i].Text + '</option');
}

It works the first time I try to populate it, but then every subsequent time thereafter, it repopulates the dropdown with the same values. Why does it ignore the new values when attempting to remake the options?

Upvotes: 0

Views: 909

Answers (2)

Adam Levitt
Adam Levitt

Reputation: 10476

The problem was caused because I was attempting to remove the disabled attribute from the dropdown. If I disable it in between repopulations, it seems to work. Very stupid bug.

Upvotes: 0

Mark
Mark

Reputation: 147

It's better to use a JSON array, try something like this:

<script>
    $(document).ready(function () {
        var myNewVals = { 4: 'Myval4', 5: 'Myval5' };

        $("#popButton").bind('click', function (event) {

            $("#mySelect").empty(); 
            $.each(myNewVals, function(val, text) {
                $("#mySelect").append($('<option></option>').val(val).html(text))
            });
        });
    });
</script>

<select id="mySelect" name="mySelect">
    <option value="1">MyVal1</option>
    <option value="2">MyVal2</option>
    <option value="3">MyVal3</option>
</select>
<input type="button" id="popButton" value="Populate!" />

Upvotes: 1

Related Questions