[英]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.