如何检查单选按钮列表中的单选按钮是否被选中

时间:2011-07-08 07:26:08

标签: javascript

早上好

我在循环浏览radiobutton列表时遇到了一些困难,以便检查它是否被选中使用Javascript。 使用C#Asp.net,程序相对简单但是使用Javascript我有点挣扎。

这是我用C#检查是否选择了radion按钮的代码。

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;
    }

}

我使用javascript的代码有点不对,我希望它可以纠正。

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;    

亲切的问候 阿里安

2 个答案:

答案 0 :(得分:1)

你可能正在寻找更像的东西:

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;

答案 1 :(得分:1)

我在这里做了一个你要问的小样本。 http://jsfiddle.net/mZhQ9/2/

编辑:分析

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
}

编辑2:作为旁注,请注意使用 “for(var loop = 0; loop&lt; document.subscribeForm.myRadio.length; loop ++)” 循环中的DOM操作。该  循环&lt; document.subscribeForm.myRadio.length条件检查文档并每次抓取单选按钮,导致大量不必要的开销。