Reputation: 8404
I am building an HTML form, and for one section of it, a cluster of HTML input fields inside of a div needs to be pushed to an array. The div and all of the fields get unique ids/names when created - in particular, one of the inputs is a select.
All of this works fine - the fields are created and pushed to the array, everything id'd correctly, etc., but I can't seem to access the select element for a jQuery change function that is supposed to come later, after the fields have been created. I tested out an inline Javascript "onchange = myFunction()" type thing and this was able to access the select element - I get why this works, but it's not going to be an acceptable solution... I really need to use a $("#id").change function.
How can I use jQuery to access a select element that's stored in an array?
this['input_array' + siteName] = [];
for (y = 0; y < numberFound; y++){
this['input_array' + siteName].push('<div id="'+routeValue+''+siteName+'Details'+y+'" class="details">Species: <select id="'+siteName+'Species'+y+'" name="species['+y+']" data-speciesNumber="'+y+'">'+speciesList+'</select></div>);
$("#"+siteName+"Species"+y+"").change(function(){
species = this.value;
speciesNumber = this.getAttribute("data-speciesNumber");
siteSpeciesNumber = displayName + "" + species + "" + speciesNumber;
document.getElementById(""+siteName+"compileField"+speciesNumber+"").value = siteSpeciesNumber;
});
};
$("#"+routeValue+""+siteName+"Details").append(this['input_array' + siteName]);
Upvotes: 0
Views: 93
Reputation: 339
The issue is not that the select is inside an array, it's that it is not yet attached to the DOM.
Try attaching the event handler as part of the element. Now when jQuery inserts the element into the document, the event binding is registered.
function $newSelect(y) {
return $('<select />', {
html: speciesList,
id: siteName + 'Species' + y,
name: 'species[' + y + ']',
data: {
speciesNumber: y
},
on: {
change: function(){
species = this.value;
speciesNumber = this.getAttribute("data-speciesNumber");
siteSpeciesNumber = displayName + "" + species + "" + speciesNumber;
document.getElementById(""+siteName+"compileField"+speciesNumber+"").value = siteSpeciesNumber;
}
}
}
}
function $newField (idNum) {
return $("<div id="'+routeValue+''+siteName+'Details'+y+'" class="details"></div>", {
html: $newSelect(idNum)
});
}
this['input_array' + siteName] = [];
for (y = 0; y < numberFound; y++){
this['input_array' + siteName].push($newField(y));
};
$("#"+routeValue+""+siteName+"Details").append(this['input_array' + siteName]);
Upvotes: 1