click or change event on radio using jquery

后端 未结 5 1601
挽巷
挽巷 2021-02-06 19:49

I have some radios in my page,and I want to do something when the checked radio changes,however the code does not work in IE:

$(\'input:radio\').change(...);


        
相关标签:
5条回答
  • 2021-02-06 20:30

    Works for me too, here is a better solution::

    fiddle demo

    <form id="myForm">
      <input type="radio" name="radioName" value="1" />one<br />
      <input type="radio" name="radioName" value="2" />two 
    </form>
    
    <script>
    $('#myForm input[type=radio]').change(function() {       
        alert(this.value);
    });
    </script>
    

    You must make sure that you initialized jquery above all other imports and javascript functions. Because $ is a jquery function. Even

    $(function(){
     <code>
    }); 
    

    will not check jquery initialised or not. It will ensure that <code> will run only after all the javascripts are initialized.

    0 讨论(0)
  • 2021-02-06 20:33

    $( 'input[name="testGroup"]:radio' ).on('change', function(e) {
         console.log(e.type);
         return false;
    });

    This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

    Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

    Lastly, I'm simply showing an alternative syntax to attach the event to the element.

    0 讨论(0)
  • 2021-02-06 20:36

    You can specify the name attribute as below:

    $( 'input[name="testGroup"]:radio' ).change(
    
    0 讨论(0)
  • 2021-02-06 20:41

    This code worked for me:

    $(function(){
    
        $('input:radio').change(function(){
            alert('changed');   
        });          
    
    });
    

    http://jsfiddle.net/3q29L/

    0 讨论(0)
  • 2021-02-06 20:41

    Try

    $(document).ready(
    

    instead of

    $('document').ready(
    

    or you can use a shorthand form

    $(function(){
    });
    
    0 讨论(0)
提交回复
热议问题