Reputation: 2733
I'm loading HTML content dynamically, specifically a element. Due to the large number of options, all options are transferred to the clients once in a JSON array, and should then be populated by the clients' browser.
For this, I'd like to attach an event to all <select>
elements, which creates a bunch of <option>
elements and selects one of them based on a criteria from the <select>
element.
This JSFiddle shows how I can achieve what I want by clicking the select element. However, I'd like to create the option tags and show the selected Index once the element is DOMReady - but I can't find an event that applies to that.
Upvotes: 0
Views: 141
Reputation: 2733
I managed to find a way by manually calling the event I'm binding to when adding the elements:
// Instead of having to "click" the select fields
// I'd like to populate the <option> tags everytime a new select item is injected into the DOM.
$(document).on("click", "select.countrylist", function() {
var select = $(this);
$(countries).each(function(i) {
var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName);
if (this.Key === select.data('selected')) option.prop("selected", true);
select.append(option);
select.get().selectedIndex = i;
});
});
// populate all existing selects
$("select.countrylist").click();
// create new select and populate it
$('#test').click(function() {
var x = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body");
// manually trigger a click which causes populating of select
x.click();
});
See this JSFiddle for a working example
Note you still need to bind the click event to $(document), and not to the select itself (it will not work).
Thanks for all help!
Upvotes: 0
Reputation: 531
Change your click handler as follows.
$('#test').click(function() {
// this select field will not be populated!
var select = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body");
$(countries).each(function(i) {
var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName);
if (this.Key === select.data('selected')) option.prop("selected", true);
select.append(option);
select.get().selectedIndex = i;
});
});
Upvotes: 0
Reputation: 3684
You could do this instead :
Store the element you just appended to the dom in a variable, then call a function populating them with this variable.
function populateSelect(elmt) {
var select = elmt;
$(countries).each(function(i) {
var option = $("<option></option>").attr("value", this.Key).text(this.Value.EnglishName);
if (this.Key === select.data('selected')) option.prop("selected", true);
select.append(option);
select.get().selectedIndex = i;
});
}
$('#test').click(function() {
// this select field will not be populated!
var elmt = $('<select data-selected="USA" class="countrylist"></select>').appendTo("body");
populateSelect(elmt);
});
Upvotes: 1