我有一個RadioButtonList和基於選擇什麼,我需要一個文本框來做不同的事情。如果選擇了第一個ListItem,我需要TextBox才允許輸入4個數字值。如果第二個ListItem被選中,我需要TextBox的功能照常。我有數字和長度驗證的功能,我知道工作,但似乎無法弄清楚如何實現那些基於它被選中。我用下面的代碼包含了數字和長度函數。我所面臨的主要問題是確定選擇哪一個,並基於該選擇,TextBox應該如何工作。如何確定基於RadioButtonList選擇的文本框將做什麼 - 使用JavaScript
// Only allows numeric values
function isNumeric(num){
var charCode = (num.which) ? num.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
else { return true; }
}
// Validates TextBox Length
function validateTextBoxLength() {
var tb = document.getElementById("TextBox1").value;
if (tb.length > 1 && tb.length != 4) {
alert("TextBox must be 4 digits.");
return false;
}
return true;
}
// Check for RadioButtonList selection
function rbSelectedValue() {
var radio = document.getElementsByName('<%= rblSearchType.ClientID %>');
var tb = document.getElementById("TextBox1").value;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
// alert("RadioButton 1 Selected");
if (tb.length > 1 && tb.length != 4) {
alert("TextBox must be 4 digits.");
return false;
}
else {
return true;
}
}
else {
// alert("RadioButton 2 Selected");
return true;
}
}
<asp:RadioButtonList ID="RadioButtonList" runat="server" AutoPostBack="true" RepeatDirection="Horizontal" onclick="rbSelectedValue()">
<asp:ListItem Value="List Item 1" Selected="True">Test 1</asp:ListItem>
<asp:ListItem Value="List Item 2">Test 2</asp:ListItem>
</asp:RadioButtonList>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
任何幫助將不勝感激,並提前感謝您!
我試着添加這個,但仍然似乎無法得到它的工作。它不會拋出任何錯誤,我通過代碼遍歷並且看不到任何不尋常的東西。你對OnSelectedIndexChanged事件有什麼看法? – Brian
@Brian:哪部分不工作? –
無論我選擇哪個ListItem,它仍然允許我在文本框中輸入任何我想要的內容。當我在函數中放置一個斷點時,它會跳過「if」語句並返回true。 - 「radio [i] .checked」顯示爲未定義。 – Brian