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
  • 16,278
  • 7
  • 48
  • 74
Sourav
  • 17,065
  • 35
  • 101
  • 159

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,824
  • 17
  • 99
  • 186
Ele
  • 33,468
  • 7
  • 37
  • 75
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
  • 367
  • 2
  • 6