2012-02-02 47 views
1

我在其旁邊有一個文本框和一個控制按鈕。單擊此按鈕將調用另一個功能,其中選擇了一些數據並將其寫回文本框。目前我的文本框是在用戶將數據提取到文本框後由用戶編輯的。我希望僅在用戶單擊按鈕並將數據提取到文本框後才能使文本框讀取,因此現在數據是出現在無法編輯的文本框中。如果用戶必須更改數據,用戶必須再次點擊按鈕來調用該功能,這將幫助我們在文本框中寫入數據。如何才能完成此操作在JavaScript中。僅在取出一些數據後才能讀取文本框

回答

6

,你可以做這樣的

HTML:

<input type="text" id="mytextbox" value="click the button below."/> 
<input type="button" value="click" onclick="changeText();"/> 

的Javascript:

function changeText(){ 
    var text_box = document.getElementById('mytextbox'); 
    if(text_box.hasAttribute('readonly')){ 
     text_box.value = "This text box is editable."; 
     text_box.removeAttribute('readonly'); 
    }else{  
     text_box.value = "This text box is read only."; 
     text_box.setAttribute('readonly', 'readonly'); 
    } 
} 

小提琴例如:http://jsfiddle.net/b7jAy/

0

您可以使用jQuery .attr()函數來設置文本字段的只讀狀態。

$('#textfield').attr('readonly', true); 
$('#textfield').attr('readonly', 'readonly'); 
+0

你不應該認爲是OP使用jquery。 – 2012-02-02 08:11:08

0

請試試JQuery。數以千計的理由將其用作Javascript框架。這裏是你的問題的迴應:

Add "readonly" to <input > (jQuery)

希望幫助,

+0

你不應該認爲OP使用jQuery。 – 2012-02-02 08:11:50

0

分配一個id屬性的文本框,說<input id=foo>,並使用

document.getElementById('foo').readOnly = true;