Handling Javascript radiobox state on page reload

Go To StackoverFlow.com

0

I've been messing around with a radiobox. I'm encountering an issue that varies depending on the browser the user uses. Basically, my goal is to generate other data on the page depending on the radiobox selected. It is important that this data remain in sync with the radiobox. Normally, this is not an issue: I run the code below when the selection changes.

However, there are issues with the way browsers often cache which checkbox is selected. IE seems to wait until the script finishes running and then switches which radiobox is selected. Firefox, on the other hand, remembers which checkbox is selected and displays it accordingly...but the checked property ignores this. I can force Firefox to keep this information synced by unchecking and checking the checkbox (the two commented out lines of code below), though this is kind of hacky.

Currently, my best idea is to generate the radio boxes via a script to kill the browsers' ability to cache them. Can anyone offer a less hacky alternative?

<br />
<input type="radio" name="DataRadio" checked="checked"
    Value="V1" onclick="doDataRadio()" />V1

<br />
<input type="radio" name="DataRadio"
    Value="V2" onclick="doDataRadio()" />V2

<br />
<input type="radio" name="DataRadio"
    Value="V3" onclick="doDataRadio()" />V3

function selCountry()
{
    var len = theForm.DataRadio.length;
    for (i = 0; i < len; i++) {
        if (theForm.DataRadio[i].checked)
        {
            chosen = theForm.DataRadio[i].value;
            //theForm.DataRadio[i].checked = false;
            //theForm.DataRadio[i].checked = true;
            alert(chosen);

        }
    }
}
2009-06-16 19:21
by Brian


2

Since you haven't shown any more code. I'm assuming that you want to call selCountry() when the page loads.

Typically with a javascript library like jQuery, running something when the page loads happens in the $(document).ready() function as show below:

$(document).ready({
  selCountry();
});

Without a javascript library, you need to it this way:

window.onload = function(){
  selCountry();
}

In this way, you ensure that the page is finished loading before finding out which radiobutton is pre-selected. This works cross-browser.

2009-06-16 20:15
by ichiban
Thank you, this not only fixes the issue but also works without losing the browser's cached information - Brian 2009-06-16 21:14
Ads