Kev
Kev

Reputation: 143

Input field readonly to users but still editable via DOM

I have an input field like so:

<input type="text" id="23" value="Something" readonly />

I have the input element readonly because I don't want users to be able to edit the field value.

However, what I would like is to be still able to manipulate the value of the element via the DOM e.g:

getElementById('23').value="Something else";

Is this possible?

Upvotes: 0

Views: 270

Answers (1)

caramba
caramba

Reputation: 22480

sure it is: but you will need to do so https://jsfiddle.net/pz1yd11u/

document.getElementById('23').value="Something else";

You were missing the document

(IDs and class names should never start with a number: read this)

Update after comment, with click event to change the input value

https://jsfiddle.net/pz1yd11u/1/

document.getElementById("kevs-button").addEventListener("click", displayNewValue);
  
function displayNewValue() {
	document.getElementById('23').value="Something else";
}
#kevs-button {
  background-color: orange;
  padding: 5px;
  width: 100px;
}
#kevs-button:hover {
  cursor: pointer;
  background-color: green;
}
<input type="text" id="23" value="Something" readonly />

<div id="kevs-button">Button</div>

Upvotes: 1

Related Questions