简体   繁体   中英

Using jQuery to trigger radio button onclick event

I have a code where I am selecting radio button using the .prop() method. Issue is I also have the onclick event on radio button is there any workaround to make it trigger an onclick event as well using jQuery

jQuery Code

/**
 * Select shipping method when selected from the list
 */
$(document).ready(function() {
    var $options = $('.shipping-method .item');

    $options.click(function(e) {
        var $current = $(this);
        e.preventDefault()
        e.stopPropagation()
        $options.removeClass('on')
        $current.addClass('on')
        $('input', $current).prop('checked', true)
    })
})

HTML Code

<li>
    <div class="item"><a href="javascript:;" class="shipping_3">Home Delivery</a>
        <input name="shipping" type="radio" class="radio" id="shipping_3" value="3" checked="checked" supportcod="1" insure="0" onclick="selectShipping(this)">
    </div>
</li>

Here you go with a solution

$current.prop('checked', true).trigger("click");

$(document).ready(function() {
  var $options = $('.shipping-method .item');

  $options.click(function(e) {
    var $current = $(this);
    e.preventDefault()
    e.stopPropagation()
    $options.removeClass('on')
    $current.addClass('on')
    $current.prop('checked', true).trigger("click");
  });
});

My suggestion would be to remove onclick attribute with a separate event listener first.
Refer jQuery.click() vs onClick .
Remove line:

e.preventDefault()

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