开发者

how to detect change for a radio button list

<ul id='theList'>
<li><input type开发者_Python百科='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)


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 -->
});


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');
   });
});


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


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' />


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜