Reputation: 621
I'm trying to get the value of the option that the user selects on a dynamically generated option in a dynamically generated select. Right now I'm just trying to get an alert to pop up though and have been thoroughly unsuccesful.
I've tried using the .change binder inside of a docuement.ready but that didn't work and I figured it may be because the elements don't exist for it to bind to. Code for the .change
$(document).ready(function () {
$(".lowerSerialSelect").change(function () {
alert("red")
});
});
Here's the code I'm using to dynamically generate the select:
if (_interface == "network" && _deviceName == "Not in Use")
{
var lowerSerialTd = document.createElement("td");
lowerSerialTd.className = "lowerSerial";
trTag.appendChild(lowerSerialTd);
var lowerSerialSelect = document.createElement("select");
lowerSerialSelect.className = "lowerSerialSelect";
lowerSerialSelect.name = "lowerSerial" + identifier;
lowerSerialSelect.id = _interface + "lowerSerial" + identifier;
var lowerSerialOption = document.createElement("option");
lowerSerialSelect.appendChild(lowerSerialOption)
for (newDevice in newNetworkDevices)
{
alert(newNetworkDevices[0]);
var lowerSerialOption = document.createElement("option");
lowerSerialOption.innerHTML = newNetworkDevices[newDevice][0];
lowerSerialOption.className = "networkMacOption";
lowerSerialOption.id = _interface + "lowerSerial" + identifier;
lowerSerialOption.value = newNetworkDevices[newDevice];
lowerSerialSelect.appendChild(lowerSerialOption)
}
lowerSerialTd.appendChild(lowerSerialSelect);
alert("Maybe");
}
So does the .change not bind to elements that aren't created yet?
If so can I get around this by rebinding everytime I create a new select? (The user will trigger the new select so it won't all be done at once)
I've also tried the $("select".on("change", "option", function() {alert("red");}); but to no avail. Any help or explanations would be appreciated.
This is on a configuration page so the code is pretty long, 800 some lines so I didn't want to post the whole thing.
Thanks
** Edit **
The html that is dynamically generated looks like this in the end:
<select class="lowerSerialSelect" name="lowerSerial2" id="networklowerSerial2">
<option></option>
<option class="networkMacOption" id="networklowerSerial2" value="0080A39166BA,192.168.1.59,47331,1363895658.22">0080A39166BA</option>
</select>
Upvotes: 0
Views: 1957
Reputation: 19740
Yeah you're spot on, .change()
is not a delegated hander. Try .on()
$('body').on('change', '.lowerSerialSelect', function() {
// code here
});
Upvotes: 2