firing a jQuery change function at document ready

醉酒当歌 提交于 2019-12-02 21:36:51

Just chain .trigger('change') to the end of the handler assignment.

 // ----------v-------v-----quotation marks are mandatory
$('input[name="country"]').change(function ()
{                                                                               
// change user instructions to be country specific
    switch ($('input[name="country"]:checked').val())
    {
        case 'US':
        $('#stateMessage1').text('2. Select a state or territory of the United States.');
        $('#stateMessage2').text('Start typing a state of the United States, then click on it in the dropdown box.');
        $('#threeSelects').show();
        $('#twoSelects').hide();
        //select via 3 steps                        
        break;           
        case 'CA':
        $('#stateMessage1').text('2. Select a province or territory of Canada.');
        $('#stateMessage2').text('Start typing a province of Canada, then click on it in the dropdown box.');
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town           
        break;         
    }
}).trigger('change');  // <--- RIGHT HERE

Or if you only want it to fire on the first element, use triggerHandler() instead.

        // ...
        $('#twoSelects').show();
        $('#threeSelects').hide();
        //select town via 2 steps - country, town           
        break;         
    }
}).triggerHandler('change');  // <--- RIGHT HERE

Why not just trigger change after selecting the appropriate radio buttons?

$('input[name=country]').change();

This is equivalent to

$('input[name=country]').trigger('change');

Before the final });, add in $('input').change();

This usually is made as:

function onChange ()
{                                                                               
    switch ($('input[name=country]:checked').val())
    ....
}

$('input[name=country]').change(onChange); // 1. attach it as event handler.
onChange();                                // 2. call it first time.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!