简体   繁体   中英

Select and trigger click event of a radio button in jquery

Upon document load, am trying to trigger the click event of the first radio button.... but the click event is not triggered .Also, tried 'change' instead of click ...but its the same result.

$(document).ready(function() {
    //$("#checkbox_div input:radio").click(function() {

    $("input:radio:first").prop("checked", true).trigger("click");

    //});



    $("#checkbox_div input:radio").click(function() {

      alert("clicked");

    });

});

Please follow the below link to the question

Example: http://jsbin.com/ezesaw/1/edit

Please help me out in getting this right. Thanks!

You are triggering the event before the event is even bound.

Just move the triggering of the event to after attaching the event.

$(document).ready(function() {
  $("#checkbox_div input:radio").click(function() {

    alert("clicked");

   });

  $("input:radio:first").prop("checked", true).trigger("click");

});

Check Fiddle

Switch the order of the code: You're calling the click event before it is attached.

$(document).ready(function() {
      $("#checkbox_div input:radio").click(function() {

           alert("clicked");

      });

      $("input:radio:first").prop("checked", true).trigger("click");

});

我的解决方案有点不同:

$( 'input[name="your_radio_input_name"]:radio:first' ).click();

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM