繁体   English   中英

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

[英]How to check if radio button in radio button list was selected

早上好

我在遍历单选按钮列表以检查是否使用 Javascript 时遇到了一些困难。 使用 C# Asp.net 的过程相对简单,但使用 Javascript 我有点挣扎。

这是我与 C# 一起使用的代码,用于检查是否选择了单选按钮。

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;    

亲切的问候阿里安

您可能正在寻找类似的东西:

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;

我做了一个你在这里问的小样本。 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 < document.subscribeForm.myRadio.length;loop++)”DOM 操作。 loop < document.subscribeForm.myRadio.length 条件每次都会检查文档并抓取单选按钮,从而导致大量不必要的开销。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM