2013-07-24 33 views
21

我知道你可以將readonly="readonly"添加到輸入字段,所以它不可編輯。但我需要使用javascript來定位輸入的id,並使其只讀,因爲我無法訪問表單代碼(它通過市場營銷軟件生成)如何使用JavaScript只讀輸入字段?

我不想禁用輸入作爲數據應該在提交時收集。

這裏是頁我在下面的建議添加至今沒有運氣:

http://bit.ly/1aI1Zxn

確保您在將來使用該人因使用<body onload="onLoadBody();">

+0

'element.setAttribute(「readonly」,「readonly」);'? http://jsfiddle.net/DerekL/e8yCd/ –

回答

37

你可以輸入元素,然後它的readOnly屬性設置爲true如下:

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

具體來說,這就是你想要:

<script type="text/javascript"> 
    function onLoadBody() { 
    document.getElementById('control_EMAIL').readOnly = true; 
    } 
</script> 

呼籲body標籤這樣onLoadBody()功能:

<body onload="onLoadBody"> 

查看演示:jsfiddle

+0

它真的在努力 –

+0

我很欣賞這種迴應,但它似乎並沒有爲我工作 - 你介意檢查:http://bit.ly/1aI1Zxn? – chris

+1

'@ chris'請找到編輯答案,解決您的問題.. – Vijay

3
document.getElementById("").readOnly = true 
1

試試這個:

document.getElementById(<element_ID>).readOnly=true; 
3
document.getElementById('TextBoxID').readOnly = true; //to enable readonly 


document.getElementById('TextBoxID').readOnly = false; //to disable readonly 
0

在這裏你有例子,如何設置只讀屬性:

<form action="demo_form.asp"> 
 
    Country: <input type="text" name="country" value="Norway" readonly><br> 
 
    <input type="submit" value="Submit"> 
 
</form>

12

以上的答案並沒有爲我工作。以下作用: document.getElementById("input_field_id").setAttribute("readonly", true);

,並刪除只讀屬性: document.getElementById("input_field_id").removeAttribute("readonly");

以及運行時加載頁面時,值得參考here