如何将ID传递给ASP.NET中的java脚本函数

时间:2012-04-11 05:46:12

标签: javascript asp.net

嗨,我有以下java脚本功能:

function EnableDisableTextBox(chkBoxId, txtBoxId) {
    var isChk = document.getElementById(chkBoxId);
    document.getElementById(txtBoxId).disabled = !(isChk.checked);
}

当我尝试调用上述功能时,通过单击复选框,它不能按预期工作

<asp:CheckBox ID="chkBachelors"
      onclick="javascript:EnableDisableTextBox('chkBachelors','txtFirstDegree');"
      runat="server" Text='<%$Resources:Resource, FirstDegree %>' TextAlign="Left"/>

<asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server" 
      MaxLength="250">&lt;/asp:TextBox>

预期结果(当用户单击chkBachelors复选框时):

if "chkBachelors" check box is checked 
    then enable "txtFirstDegree" text box
else 
    disable "txtFirstDegree" text box   

有什么问题以及如何解决?

2 个答案:

答案 0 :(得分:1)

    <asp:CheckBox ID="chkBachelors"
              onclick="EnableDisableTextBox(this);"
              runat="server" Text='' TextAlign="Left"/>

        <asp:TextBox ID="txtFirstDegree" CssClass="form-text" runat="server" 
              MaxLength="250"></asp:TextBox>


<script language ="javascript" type="text/javascript">
       function EnableDisableTextBox(checkbox)
       {
           var txtBoxId= "<%=txtFirstDegree.ClientID%>";
           document.getElementById(txtBoxId).disabled = !(checkbox.checked);
       }
</script>

答案 1 :(得分:0)

&LT;%= chkBachelors.ClientID%GT;和&lt;%= txtFirstDegree.ClientID%&gt;将给出Asp.Net控件的客户端ID。您不需要明确传递它们

function EnableDisableTextBox() {
            var isChk = document.getElementById(<%=chkBachelors.ClientID%> );
            document.getElementById(<%=txtFirstDegree.ClientID%>).disabled = !(isChk.checked);
        }