开发者

How to check if radio button in radio button list was selected

Good morning

I am having some difficuly in looping through a radiobutton list in order to check if it was selected or not using Javascript. With C# Asp.net the procedure is relatively easy b开发者_运维问答ut with the Javascript I am struggling a little.

This is the code I use with C# to check if the radion button was selected.

protected void Button1_Click(object sender, EventArgs e)
{
    string radValue = RadioButtonList1.SelectedValue.ToString();

    if (radValue == "")
    {
        lblError.Text = "Please select neigbourhood";
    }
    else
    {
        lblError.Text = "You come from " + radValue;
    }

}

The code I use with javascript is a little faulty and I was hoping it could be corrected.

var radNeighbourhood;

for(var loop=0; loop < document.subscribeForm.myRadio.length; loop++)
{
    if(document.subscribeForm.myRadio[loop].checked == true)
    {
        radNeighbourhood = document.subscribeForm.myRadio[loop].value;
        break;

    }
    else
    {
        alert("Please select a neigbourhood");
        return false;
    }
}
return true;    

Kind regards Arian


I made a small sample of what you 're asking here. http://jsfiddle.net/mZhQ9/2/

EDIT: analysis

var radioButtons = document.subscribeForm.myRadio; //it is crucial to store the DOM information in a variable instead of grabbing it, each single time. (DOM operations are EXTREMELY slow)
var len = radioButtons.length; //same as before
var found = false; //our flag - whether something was found or not

while( len-- > 0 ) { //decreasing the counter (length of radio buttons)
    if( radioButtons[len].checked === true ) { //if we find one that is checked
        found = true; //set the flag to true
        break; //escape the loop
    }
} 

if( found ) { //if our flag is set to true
    alert( radioButtons[len].value );
    return radioButtons[len].value; //return the value of the checked radiobutton (remember, when we broke from the While-loop, the len value remained at the 'checked' radio button position)
}
else { 
    alert( "Please select a neigbourhood" );
    return false; //else return false
}

EDIT 2: As a sidenote please be careful of using "for(var loop=0; loop < document.subscribeForm.myRadio.length; loop++)" DOM operations within a loop. the loop < document.subscribeForm.myRadio.length condition checks the document and grabs the radio buttons every single time, resulting in lots of unecessary overhead.


You might be looking for something more like:

var radNeighbourhood;
for (var loop=0; loop < document.subscribeForm.myRadio.length; loop++)
{
    if (document.subscribeForm.myRadio[loop].checked == true)
    {
        radNeighbourhood = document.subscribeForm.myRadio[loop].value;
        break;
    }
}

if (!radNeighbourhood)
{
    alert("Please select a neighbourhood");
    return false;
}

alert("You come from " + radNeighbourhood);
return true;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜