I have 3 textboxes, all with the same id's that I process into ASP by bringing it into a controller array
I have a link that adds an unlimited number of textboxes below the first 3.
My current change statement:
$('input.#invent').change(function () {
works fine for the change event on the first textbox, but the others with the same information do not fire it when changed
What is the best strategy for getting the change event to fire when any of the 3+ textboxes change??
Best strategy (95% of the time): use a class to add a listener for multiple elements. ID's are expected to be unique. Classes are made for this and will give you the most extensibility in the future.
HTML:
<input type="text" name="input1" class="invent" />
<input type="text" name="input2" class="invent" />
jQuery:
$('.invent').change(function () {
// Do magical things
});
For the other 5%:
If you'd rather use unique IDs or unique field names instead of a single class as described in the selected answer, you can add a listener for multiple uniquely named elements like so:
HTML:
<input type="text" name="something1" id="invent1" />
<input type="text" name="something2" id="invent2" />
<input type="text" name="something3" id="invent3" />
you can use jQuery multiple selectors:
$('#invent1, #invent2, #invent3').change(function () {
// Do magical things
});
OR you can use jQuery starts with attribute selector:
//target based on what input id starts with
$('[id^="invent"]').change(function () {
// Do magical things
});
// OR target based on input name attribute starts with
$('input[name^="something"]').change(function () {
// Do magical things
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With