有一個CheckBoxList(選擇可以是多個)和默認情況下不顯示的文本框。要求如下:
1.當用戶在CheckBoxList中單擊「其他」時,應顯示文本框。
2.由於TextBox在顯示時是必需的,因此當TextBox不顯示時應驗證器被禁用。顯示/隱藏文本框和啓用/禁用基於CheckBoxList選擇的文本框驗證
的.aspx頁面內容
<label for="labelSelection">Please Select:</label>
<asp:CheckBoxList ID="cblSelection" onclick="ShowOtherInfo(this)" runat="server">
<asp:ListItem Text="AAA" Value="1" />
<asp:ListItem Text="BBB" Value="2" />
<asp:ListItem Text="Other" Value="0" />
</asp:CheckBoxList>
<div id="OtherInfo" style ='display:none'>
<label for="labelOtherInfo">Enter detail if "Other" is selected: </label>
<asp:TextBox ID="OtherInfoTextBox" runat="server" />
<asp:RequiredFieldValidator ID="rfvOtherInfo" ControlToValidate="OtherInfoTextBox"
ErrorMessage="Enter other info" SetFocusOnError="true" Display="Dynamic" runat="server" />
</div>
<div>
<asp:Button ID="buttonSubmit" runat="server" Text="Submit" CausesValidation="true" OnClientClick="ShowOtherInfo()" OnClick="buttonSubmit_Click" />
</div>
的Javascript放置的.master頁面上
function ShowOtherInfo() {
var OI = document.getElementById('OtherInfo');
var CheckLists = document.getElementById('cblSelection');
var checkbox = CheckLists.getElementsByTagName("input");
if (checkbox[2].checked) {
document.getElementById('OtherInfo').style.display = "block";
ValidatorEnable(document.getElementById('rfvOtherInfo'), true);
} else {
document.getElementById('OtherInfo').style.display = "none";
ValidatorEnable(document.getElementById('rfvOtherInfo'), false);
}
}
因爲我更喜歡使用JavaScript進行驗證,我已經嘗試了CheckBoxList的和的OnClientClick事件的onchange/onclick事件爲 「提交」按鈕,但它們都不起作用。任何幫助是極大的讚賞。
初次發佈後,我嘗試用Onclick =「ShowOtherInfo(this)」替換CheckBoxList中的OnSelectedIndexChanged =「ShowOtherInfo」。和代碼隱藏在cs文件是:
public void DisplayOtherInfo(object sender, EventArgs e) {
CheckBoxList cblSelection = (CheckBoxList)myFormView.FindControl("cblSelection");
RequiredFieldValidator rfvOtherInfo = (RequiredFieldValidator)myFormView.FindControl("rfvOtherInfo");
HtmlGenericControl OtherInfo = new HtmlGenericControl("OtherInfo");
for (int i = 0; i < cblSelection.Items.Count; i++)
{
if (cblSelection.Items[2].Selected == true)
{
OtherInfo.Style["display"] = "block";
rfvOtherInfo.Enabled = true;
}
else
{
OtherInfo.Style["display"] = "none";
rfvOtherInfo.Enabled = false;
}
}
}
但仍文本框甚至不顯示的,不是說禁止驗證。
「更喜歡使用JavaScript進行驗證」 - 這是不好的。始終使用服務器驗證,然後爲用戶體驗添加客戶端驗證 – Ian 2013-03-20 06:02:19
對不起,其實並不意味着「更喜歡」。無論什麼作品都很好,但我認爲Javascript可能對用戶體驗更好。 – Denis 2013-03-20 12:40:25
我嘗試用Onclick =「ShowOtherInfo(this)」替換CheckBoxList中的OnSelectedIndexChanged =「ShowOtherInfo」。代碼隱藏是: – Denis 2013-03-20 16:12:37