简体   繁体   中英

jquery event are not triggered automatically

I have 2 radio buttons that will do something when either is checked. And here is a JQuery that is tied to them:

$('input[name=24hours]:radio').on('change', function() {
    if($('#hours24y').is(':checked')) 
    { $('table').hide(); }
    else if ($('#hours24n').is(':checked')) 
    { $('table').show(); }

Also in the form I have a reset button. I tried to trigger the event above when the reset button is clicked like so:

$('[type=reset]').on('click', function(){
    $('input[name=24hours]:radio').triggerHandler('change');
});

The problem is, when the reset button is click for the first time, it only change the radio button to its initial state. The trigger jquery will only happen when the reset button is clicked again. So, how can I make the trigger jquery automatically run on first click of reset button?

EDIT: Here's the example of action. When I check on the radio button #hours24n, a table will be shown. and if I check on the radio button #hours24y, the same table will be hidden.

let's say initially, the table is shown with #hours24n is checked. Then, I check on #hours24y thus the table will be hidden. Now, what I expect after clicking the reset button is, #hours24n will be checked and at the same time, the table will be shown again.

jQuery

  $('input').on('change', function() {
        if ($('.radio[name=24hours]').is(':checked')) {
        { 
$('.table').fadeTo(500, 1);
this.checked = false;}

        if($('#hours24n').is(':checked'))
        { 
$('.table').fadeOut(500, 0);
this.checked = false; }
        }
    });

Try that, then create your table with the class 'table', saves the hassle if you need to apply more tables without using this method. Format your cells within;

<table class="table" style="opacity: 0"></table>

Try adding closing bracket, parentesis to change handler }) , utilizing selector 'input[name=24hours][id=hours24n]:radio' , setting .prop("checked", true) before calling .triggerHandler('change') at click event , calling .click() event to set #hours24n intially checked

 $(function() { $('input[name=24hours]:radio').on('change', function() { if ($('#hours24y').is(':checked')) { $('table').hide(); } else if ($('#hours24n').is(':checked')) { $('table').show(); } }) $('[type=reset]').on('click', function() { $('input[name=24hours][id=hours24n]:radio') .prop("checked", true).triggerHandler('change'); }).click(); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <input type="radio" name="24hours" id="hours24y" /> <input type="radio" name="24hours" id="hours24n" /> <input type="reset" /> <table> <tbody> <tr> <td> checked </td> </tr> </tbody> </table> 

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