Paul
Paul

Reputation: 117

How to make an input field readonly

I want to make the input field readonly. The below code is working for me. But, if the page is refreshed the input fields will become readonly and I cant enter anything in the input field. I want that to become readonly only after the data is present in the input field.

      const disableInputs = function() {
      sessionStorage.disableInputs = 'true';
      document.getElementById('firstname').disabled = true;
      document.getElementById('lastname').disabled = true;
      document.getElementById('email').disabled = true;
      document.getElementById('mew').disabled = true;
      };
      if (sessionStorage.disableInputs === 'true') disableInputs();
      document.getElementById('myButton').onclick = disableInputs;

Any help is much appreciated.Thank you

Upvotes: 0

Views: 2615

Answers (3)

Sankar Subburaj
Sankar Subburaj

Reputation: 5042

In HTML:

<input type="text" id="someid" name="somename" readonly="readonly" value="">

In PHP:

 <input type="text" id="someid" name="somename" <?php if($value) { 
 echo 'readonly="readonly"'; } ?> value="<?php echo $value ?>">

In Javascript:

<script>
 function disableInputField() {
  if (document.getElementById("someid").value) {
    document.getElementById("someid").readOnly = true;
  }
  else {
    document.getElementById("someid").readOnly = false;
  }
 }
</script>

All together:

<input type="text" id="someid" name="somename" <?php if($value) { 
 echo 'readonly="readonly"'; } ?> value="<?php echo $value ?>" onblur="Javascript:disableInputField();">

Upvotes: 2

dcangulo
dcangulo

Reputation: 2107

Use this: document.getElementById("your-id").readOnly = true;

Source: https://www.w3schools.com/jsref/prop_text_readonly.asp

Snippet from w3schools: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_text_readonly2

function myFunction() {
    document.getElementById("myText").readOnly = true;
}
<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="myText">

<p>Click the button to set the text field to read-only.</p>

<p><strong>Tip:</strong> To see the effect, try to type something in the text field before and after clicking the button.</p>

<button onclick="myFunction()">Try it</button>

</body>
</html>

Upvotes: 1

sonu kumar
sonu kumar

Reputation: 7

you can just add readonly like required in html for eg.

Upvotes: 0

Related Questions