Reputation: 419
I have a couple of drop down boxes with ids country1, country2, ... When the country is changed in a drop down the value of the country shoudl be displayed in an alert box.
if I add the onchange handler for one box like this it works fine:
$('#country1') .live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
But I need to do this dynamically for all drop down boxes so I tried:
$(document).ready(function() {
$('[id^=country]') .each(function(key,element){
$(this).live('change', function(e){
var selectedCountry = e.target.options[e.target.selectedIndex].value;
alert(selectedCountry);
});
});
});
This doesn't work. No syntax error but just nothing happens when the seleted country is changed. I am sure that the each loop is performed a couple of times and the array contains the select boxes.
Any idea on that?
Thanks, Paul
Upvotes: 3
Views: 11870
Reputation: 298176
The reason .live()
existed was to account for elements not present when you call the selector.
$('[id^=country]') .each(function(key,element){
iterates over elements that have an id
that starts with country
, but only those that exist when you run the selector. It won't work for elements that you create after you call .each()
, so using .live()
wouldn't do you much good.
Use the new style event delegation syntax with that selector and it should work:
$(document).on('change', '[id^=country]', function(e) {
// ...
});
Replace document
with the closest parent that doesn't get dynamically generated.
Also, consider adding a class to those elements along with the id
attribute.
Upvotes: 6
Reputation: 94101
Instead of incremental ids I'd use a class. Then the live
method is deprecated but you may use on
with delegation on the closest static parent or on document
otherwise.
$('#closestStaticParent').on('change', '.country', function() {
// this applies to all current and future .country elements
});
You don't need an each loop this way; plus events are attached to all the elements in the jQuery collection, in this case all .country
elements.
Upvotes: 5