Reputation: 117
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
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
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