2010-03-05 29 views
0

我有一個默認情況下設置爲ReadOnly的多行文本框。我想要一個頁面上的按鈕來更改控件以允許它被編輯。我希望這段代碼能夠在客戶端運行,因爲頁面呈現速度很慢,我想避免發佈帖子。使用客戶端代碼從文本框中刪除READONLY屬性

我遇到的問題是我寫的刪除readonly屬性的javascript代碼似乎沒有任何效果。我發佈了一個簡明的例子,說明你的評論問題。

<%@ Page Language="C#" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<script runat="server"> 

</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Test</title> 
    <script type="text/javascript" language="javascript"> 
    function EnableEditing() { 
    var e = document.getElementById("<%=TextBox1.ClientID%>"); 
     var result = e.removeAttribute("readonly"); 
     alert(result); 

    } 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div>  </div> 
<asp:TextBox ID="TextBox1" runat="server" ReadOnly="True" TextMode="MultiLine">test</asp:TextBox>   
     <input id="Button1" onclick="EnableEditing()" type="button" value="Remove RO" /> 

    </form> 
</body> 
</html> 

回答

3

TextBox1的是服務器端的ID,

嘗試

var e = document.getElementById("<%=TextBox1.ClientID%>"); 

var result = e.removeAttribute("readonly",0); 

,或者如果你不想讓CASEINSENSITIVE搜索

var result = e.removeAttribute("readOnly");//note upercase Only 
+0

檢查源代碼時,文本框的ID爲TextBox1。 但是我爲了準確性而讓你改變了。它沒有任何區別。您仍然無法編輯文本框。 – Aheho 2010-03-05 18:59:01

+0

@Aheho通過0中的第二個參數(我推薦我的代碼)告訴它做一個不區分大小寫的搜索,你也應該使用ClientId,它可以確保你得到正確的Id,它不總是相同的,特別是如果控件嵌套在其他控件中 – Pharabus 2010-03-05 19:09:14

+0

工作正常。謝謝! – Aheho 2010-03-05 19:40:04

1

使用var e = document.getElementById("<%=TextBox1.ClientID%>");

鋁因此,如果要在回發中讀取修改的文本,則無法在服務器控件上設置只讀屬性。您必須將其設置在客戶端上,如下所示:TextBox1.Attributes("readOnly") = "readOnly";

+0

感謝您的澄清。我意識到,當文本框更改不在回發。 – Aheho 2010-03-06 16:50:02

相關問題