[Solved] 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:


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

Enquirer: chris


Solution #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;

Call this onLoadBody() function on body tag like:

<body onload="onLoadBody">

View Demo: jsfiddle.

Respondent: Vijay

Solution #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:

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

Respondent: Charlie Haley

Solution #3:

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

document.getElementById('TextBoxID').readOnly = false;   //to  disable readonly
Respondent: Mumthezir VP

Solution #4:

document.getElementById("").readOnly = true
Respondent: gezzuzz

Solution #5:

Try This :

Respondent: Sandiip Patil

Solution #6:

I think you just have readonly=”readonly”

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

Respondent: Liam

Solution #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">
Respondent: bobofrut

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.