How to make a input field readonly with JavaScript?

心不动则不痛 提交于 2020-05-09 19:22:26

问题


I know you can add readonly="readonly" to an input field so its not editable. But I need to use javascript to target the id of the input and make it readonly as I do not have access to the form code (it's generated via marketing software)

I don't want to disable the input as the data should be collected on submit.

Here is the page I have added in the below suggestion with no luck so far:

https://www.pages05.net/engagedigital/inputReadOnly/test?spMailingID=6608614&spUserID=MTI5MDk4NjkzMTMS1&spJobID=Nzk4MTY3MDMS1&spReportId=Nzk4MTY3MDMS1

Make sure you use <body onload="onLoadBody();"> for anyone using this in the future.


回答1:


You can get the input element and then set its readOnly property to true as follows:

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

Specifically, this is what you want:

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

Call this onLoadBody() function on body tag like:

<body onload="onLoadBody">

View Demo: jsfiddle.




回答2:


The above answers did not work for me. The below does: document.getElementById("input_field_id").setAttribute("readonly", true);

And to remove the readonly attribute: document.getElementById("input_field_id").removeAttribute("readonly");

And for running when the page is loaded, it is worth referring to here.




回答3:


document.getElementById("").readOnly = true



回答4:


document.getElementById('TextBoxID').readOnly = true;    //to enable readonly


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



回答5:


Try This :

document.getElementById(<element_ID>).readOnly=true;



回答6:


I think you just have readonly="readonly"

<html><body><form><input type="password" placeholder="password" valid="123" readonly=" readonly"></input>




回答7:


Here you have example how to set the readonly attribute:

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


来源:https://stackoverflow.com/questions/17825537/how-to-make-a-input-field-readonly-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!