Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a input field readonly with JavaScript?

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.

like image 877
chris Avatar asked Jul 24 '13 04:07

chris


People also ask

How do you make an input field read only in HTML?

The readonly attribute of <input> element in HTML is used to specify that the input field is read-only. If an input is readonly, then it's content cannot be changed but can be copied and highlighted.

How do I make a read only field editable in JavaScript?

getElementById("input_field_id"). setAttribute("readonly", true); And to remove the readonly attribute: document. getElementById("input_field_id").

How do you make a field Uneditable?

The readonly attribute makes a form control non-editable (or “read only”). A read-only field can't be modified, but, unlike disabled , you can tab into it, highlight it, and copy its contents. Setting the value to null does not remove the effects of the attribute. Instead use removeAttribute('readonly') .


1 Answers

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.

like image 151
Vijay Avatar answered Sep 21 '22 11:09

Vijay