2011-09-22 19 views
0

我有一个复选框,可以在检查时禁用2个文本框。当它未被选中时,它将启用复选框。这里是JavaScript:禁用检查时的文本框已更改

function enableField() { 
    prePracticeCodeTextBox = document.getElementById('prePracticeCodeTextBox'); 
    preContactTextBox = document.getElementById('preContactTextBox'); 
    checkTheBox = document.getElementById('CheckBox1'); 
    if (checkTheBox.checked == true) { 
     prePracticeCodeTextBox.disabled = false; 
     preContactTextBox.disabled = false; 

    } 
    else { 
     prePracticeCodeTextBox.disabled = true; 
     preContactTextBox.disabled = true; 
    } 
} 

下面是HTML:

<dl> 
    <dt><label for="CheckBox1">PreAnalytical?</label></dt> 
    <dd> <asp:CheckBox ID="CheckBox1" runat="server" CausesValidation="false" 
          Visible="true" OnCheckChanged="enableField()"/></dd> 
</dl> 
<dl> 
    <dt><label for="prePracticeCodeTextBox">Practice Code:</label></dt> 
    <dd><asp:TextBox ID="prePracticeCodeTextBox" runat="server" Enabled="False" /></dd> 
</dl> 
<dl> 
    <dt><label for="preContactTextBox">Contact:</label></dt> 
    <dd><asp:TextBox ID="preContactTextBox" runat="server" Enabled="False" /></dd> 
</dl> 

的JavaScript函数不会被调用的。

我在做什么错?

回答

3

尝试使用onclick来代替。使用下面的代码对你的代码注册它背后:

CheckBox1.Attributes.Add("onclick", "enableField();"); 

顺便说一句,你将不能够为您在asp.net web表单使用默认设置的应用程序做达到的元素。你需要得到将要呈现的元素的ClientID:

function enableField() { 
    prePracticeCodeTextBox = document.getElementById('<%=prePracticeCodeTextBox.ClientID%>'); 
    preContactTextBox = document.getElementById('<%=preContactTextBox.ClientID%>'); 
    checkTheBox = document.getElementById('<%=CheckBox1.ClientID%>'); 
    if (checkTheBox.checked == true) { 
     prePracticeCodeTextBox.disabled = false; 
     preContactTextBox.disabled = false; 

    } 
    else { 
     prePracticeCodeTextBox.disabled = true; 
     preContactTextBox.disabled = true; 
    } 


} 

如果您在.NET 4开发,请阅读下面的文章:

http://www.tugberkugurlu.com/archive/we-lovenet-4-clean-web-control-ids-with-clientidmode-property-to-static-and-predictable

+0

我并不需要使用<%= ...它没有它的工作 –

+1

然后,这意味着您的应用程序被配置为生成干净的ID。请记住它。如果您将代码放入ContentPlaceHolder(使用母版页)时,元素的ID将肯定会更改。 – tugberk

1

变化OnCheckChanged="enableField()变为onclick="enableField();"。您正在使用服务器控件。 OnCheckChanged是asp.net CheckBox控件的事件。

+0

感谢这么多!!!!!!!!!!!!!!!!!!!!!!!!!!!!! –

0

功能enableField(){

prePracticeCodeTextBox =.getElementById('<%=prePracticeCodeTextBox.ClientID%>'); 
preContactTextBox = document.getElementById('<%=preContactTextBox.ClientID%>'); 
checkTheBox = document.getElementById('<%=CheckBox1.ClientID%>'); 

if (checkTheBox.checked == true) { 

    prePracticeCodeTextBox.disabled = false; 
    preContactTextBox.disabled = false; 

} 
else { 

    prePracticeCodeTextBox.disabled = true; 
    preContactTextBox.disabled = true; 
} 

}