disparando una función de cambio de jQuery cuando el documento está listo

My change function allows users to switch from country to country and get different text and features. It works when changing country selections. But at initial page load, it does not fire jQuery change to set the hide and show text divs for the default / initial country.

Both divs display at initial page load. When I change away and then back to the default/initial country, change fires, hide and show fire, and shows the proper information and features.

He tratado document.ready with a change function both inside the switch selections and outside the change function. Neither work - they don't fire the hide, show and other jQuery in the switch cases at doc ready. Its not clear to me whether 'ready' is a valid trigger event.

También he intentado:

$('input[name=country]').value('US').trigger('click'); 

but it broke the change function. Here's the code. The country selection below is just 2 countries to keep it simple, but actually, there are many.

$(document).ready(function()
{
//1st tier - select country via radio buttons:           
//Initialize country
$('input[name=country]:first').attr('checked', true);   //Set first radio button (United States)
//$('input[name=country]:first').attr('checked', true).trigger('ready');  //sets 1st button, but does not fire change
//$('input[name=country]:first').trigger('click'); //sets 1st button, but does not fire change

$('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;         
    }
});
});

preguntado el 16 de mayo de 11 a las 20:05

4 Respuestas

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() en vez.

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

contestado el 17 de mayo de 11 a las 00:05

This works. Thanks. It loops 25 times. Is there another way to do it that does not loop - or am I being picky ;-) I do want it to fire the entire change function because any one of many countries could be the initial condition - so triggerHandler on the first is not it. - Mike_Laird

@Mike_Laird: If you're saying that you only want it to trigger for the checked one, then do this instead: .filter(':checked').trigger('change'); - user113716

You nailed it! awesome. Change fires only once on load and once for each individual change thereafter. Show, hide, etc. do their stuff correctly. Thanks very much. - Mike_Laird

This solution loops repeatedly, in my case the situation is a drop down menu change called #employeeDropDown, I don't know how to get it to load the default selection on page load. - Nathan McKaskle

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

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

Esto es equivalente a

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

contestado el 17 de mayo de 11 a las 00:05

This does not fire the change function. Show and hide don't execute. - Mike_Laird

It does - all the other answers on the page do the same thing. There must be something else that's causing it not to work - perhaps where you placed the trigger call. - no.good.at.coding

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

contestado el 17 de mayo de 11 a las 00:05

This works. Thanks. It loops 25 times on the initial page load. Is there another way to do it that does not loop - or am I being picky ;-) Afterwards for changes to a country, it executes only once. So in terms of behavior, it acts the same as the patrick dw suggestion above. - Mike_Laird

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.

contestado el 17 de mayo de 11 a las 00:05

You may have something here, but I'm a novice and I could not get your suggestion working. The page would not load. The instructions are too terse. If you care to expand the suggestion into more implementation detail, I'll try it again. - Mike_Laird

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.