一千萬個為什麽

搜索

如何檢查單選按鈕列表中的單選按鈕是否被選中

早上好

我在循環瀏覽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;    

親切的問候 阿裏安

最佳答案

I made a small sample of what you 're asking here. 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
}

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.

轉載註明原文: 如何檢查單選按鈕列表中的單選按鈕是否被選中