2012-04-11 60 views
0

嗨Java腳本函數,我有以下的Java腳本函數:如何通過ID在ASP.NET

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 

什麼問題以及如何解決?

+0

哪個asp.net版本?你介意使用jQuery嗎? – naveen 2012-04-11 06:41:38

回答

0

<%= chkBachelors.ClientID%>和<%= txtFirstDegree.ClientID%>會給客戶端ID的Asp.Net控制。你不需要通過他們明確地

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

你的意思是說
代替的onclick = 「JavaScript的:EnableDisableTextBox( 'chkBachelors', 'txtFirstDegree');」我必須使用onclick =「javascript:EnableDisableTextBox('<%= chkBachelors.ClientID%>','<%= txtFirstDegree.ClientID%>');」 – Vipul 2012-04-11 06:00:37

+0

爲什麼你需要將它們傳遞給EnableDisableTextBox.Moreover這裏的ID是服務器端的ant,它在客戶端不會是相同的,除非你將CLIENTIDMODE設置爲只適用於.net 4.0的靜態。 – 2012-04-11 06:04:04

+0

沒有必要通過ID作爲除非複選框和TextBox控件參數是中繼器或數據網格,你給 – 2012-04-11 06:14:02

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> 
+0

工作謝謝dhinesh但如果我有多個對這樣的複選框和文本框的? – Vipul 2012-04-11 06:06:26

+0

@Vipul:UserControl將是最佳選擇。 – dhinesh 2012-04-11 06:15:53