Sourav
Sourav

Reputation: 17530

Append fails to add option to dynamically loaded option list with optgroup

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>

Upvotes: 0

Views: 38

Answers (2)

Ele
Ele

Reputation: 33726

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

Upvotes: 3

Jirka Vrba
Jirka Vrba

Reputation: 377

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.

Upvotes: 3

Related Questions