Reputation: 71288
<ul id='theList'>
<li><input type='radio' name='foo' val='1' /></li>
<li><input type='radio' name='foo' val='2' /></li>
<li><input type='radio' name='foo' val='3' /></li>
<li><input type='radio' name='foo' val='4' /></li>
<li><input type='radio' name='foo' val='5' /></li>
</ul>
I want to show an alert('hi') when some radio input is selected. I tried this:
$(function(){
$('#theList input[type="radio"]').live('change', function(){
alert('hi');
});
});
and it doesn't work. (I use live because I change the content of the ul via ajax)
Upvotes: 0
Views: 1155
Reputation: 163
you can try this simple jquery event which triggered whenever user click on radio button.
$(document).on('change', '#theList li input', function() {
alert('hi');
});
This event triggers whenever someone click on radio button
Upvotes: 0
Reputation: 2338
You could bind the event to the parent element instead, this way it will catch the change event of any input[type="radio"]
tag inside, no matter if the tag came from the server at first load or if it was added later to the DOM:
$(function(){
$('#theList').on('change', 'input[type="radio"]', function(){
console.log("hi: ", $(this).val())
});
});
Also, notice that your inputs should have their value
property set instead of val
. For example:
<input type='radio' name='foo' value='1' />
Upvotes: 0
Reputation: 9041
You could also use .trigger() in your ajax at the point where the checkbox gets selected.
I've coded up an example where clicking a link triggers the change:
jQuery
$('#click').click(function(){
$('#theList input[val="2"]').click().trigger('contentchanged')
});
$('#theList input[type="radio"]').bind('contentchanged', function() {
alert('hi');
});
Check it out in action on jsfiddle - http://jsfiddle.net/HQs8g/
Hope this helps Alex
Upvotes: 0
Reputation: 474
Your 'change' event handler is probably not being bound correctly. live() doesn't always work when you are dynamically altering the elements you want to bind to.
just to test, try ajaxComplete()
something like :
$('#theList').ajaxComplete(function(){
<!-- attach change event -->
});
Upvotes: 1
Reputation: 5609
Use .die() so you don't stack multiple click events to the radios. Also, it's the "click" event you need, not "change".
$(function(){
$('#theList input[type="radio"]').die().live('click', function(){
alert('hi');
});
});
Upvotes: 1