Your first call to
change attaches an event handler to be triggered when the value in the selected fields change. The second call to
change (without any parameters) invokes that handler immediately, thus initialising the page based on the current state.
Your code didn't work for me, but the following does. Your calls to
attr are setting the
selected attribute on the field (which has no effect), not choosing the selected item. Use the
:checked selector instead.
- $(function() {
- //Initialize country
- $('input[name=country]:first').attr('checked', true); //Set first radio button (United States)
- //Enable changes to the country selection and change page text as the selections change
- $('input[name=country]').change(function() {
- // change the page per this logic
- switch ($('input[name=country]:checked').val()) {
- case 'United_States':
- $('#stateMessage').text('Select a state or territory of the United States.'); break;
- case 'Canada':
- $('#stateMessage').text('Select a province or territory of Canada.'); break;
- default:
- $('#stateMessage').text('Test - all other');
- };
- }).change();
- });
Also, you should wrap your radio buttons and their text in
label elements to allow them to be chosen by clicking on the text too.
- <p><label for="country">1. Click a country: </label>
- <label><input type="radio" id="unitedStates" name="country" value="United_States">United States</label>
- <label><input type="radio" id="canada" name="country" value="Canada">Canada</label>
- <label><input type="radio" id="other" name="country" value="Other">Other</label>
- </p>