0

Appending a single option to a dynamically loaded select fails without any error. This is jQuery code

$("#problem").load("docType.html");
$("#problem").append("<option value='All'>All</option>");

This loads options with option group from the external file successfully but fails to append the 'All' option. No error or warning though !

docType.html contents

<optgroup label="Billing">
<option value="Incorrect Bill" selected="selected">Incorrect Bill</option>
<option value="High Bill">High Bill</option>
</optgroup>
<optgroup label="Other">
<option value="Others">Others</option>
</optgroup>
Huangism
  • 15,899
  • 5
  • 47
  • 67
Sourav
  • 16,318
  • 34
  • 98
  • 153

2 Answers2

3

You need to pass a callback because load function makes an async request.

$("#problem").load("docType.html", "", function() {
    $(this).append("<option value='All'>All</option>");
});

Resource

halfer
  • 19,471
  • 17
  • 87
  • 173
Ele
  • 32,412
  • 7
  • 33
  • 72
3

The load() method has an optional callback parameter.

You can use it here like

$("#problem").load("docType.html",, function (){
    $("#problem").append("<option value='All'>All</option>")
});

What happens is that jQuery starts loading docType.html and appends the All option to #problem. But this append ends before the docType.html loads.

After it loads it overwrites the original content with the All option.

Hope it helps.

Jirka Vrba
  • 347
  • 2
  • 6