jquery - radio button not checked on page load, but checked on same function call later

Posted by Bill Zimmerman on Stack Overflow See other posts from Stack Overflow or by Bill Zimmerman
Published on 2010-04-10T16:28:41Z Indexed on 2010/04/10 16:33 UTC
Read the original article Hit count: 409

Filed under:
|

Hi, I'm having a strange problem with jquery.

When my page loads, I dynamically create some simple radio buttons in a special i've created. However, the default radio button is not checked. It is checked however when the change() event is triggered later, but is never checked the first time. Can someone help? I am certain that the change() event is triggered on the page load, because the rest of the HTML is added dynamically and I can see it.

The basic idea is when the page loads, I bind an event handler, and then immediately call it to make sure that the default options are loaded.

$(document).ready(function() {
    $(".options select[name=App]").change(onAppChange);
    //trigger the change function in the dropdown to populate default options
    $(".options select[name=App]").change()
}

Here is the simple onAppChange() function:

function onAppChange()
{

    var val = $(this).val();
    var app_options = $(this).closest(".options").find(".app_options");

    //clear the app_options
    app_options.empty();
    var newOptions = '';

    switch(val) {
        case 'testapp':
            newOptions='\
<fieldset>\
    <legend>TestApp</legend>\
Option 1:\
<label>\
<input type="radio" name="option1" value="value1" checked>\
Value1\
</label>\
\
<label>\
<input type="radio" name="option1" value="value2">\
value2\
</label>\
\
</fieldset>';

            break;

        case 'todo': //for testing
            newOptions='FOO';
            break;    
    }

    app_options.append(newOptions); 
}

Yes, I am aware that I could use javascript to automatically select a radio button again, but I asked this question because I wanted to understand why this is happening.

When using and , there doesn't seem to be any problem. Only with radio buttons. Why does the behavior differ when the same change() event is triggered? What is going on behind the scenes?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about radiobutton