lfaruqui
lfaruqui

Reputation: 47

How do I make an html text input readonly but be able to update with a script?

I have these inputs that take the values of a from a in my table when I click on a row. I want to make it so that the user cannot change the input themselves but want to bring values into them when a user clicks a table row. I will be passing these inputs in as a form. I know that when the input is like this: that it will not be updated. Is there any other way to do it with an input. Is there a different type of tag I can use that can be passed through a form?

Upvotes: 1

Views: 942

Answers (2)

Sombir Kumar
Sombir Kumar

Reputation: 1891

Try disabled keyword as here

<div id="my-display">This is a value</div>
<input id="my-input" name="my-input" type="text" disabled/>

You can change the value by javascript as below:

document.querySelector('#my-input').value = 'the value you want to enter by javascript';

Upvotes: 0

David
David

Reputation: 219077

Rather than a read-only <input>, I'd go with a combination of a display element and a hidden form element. Something like:

<div id="my-display">This is a value</div>
<input id="my-input" name="my-input" type="hidden" />

And in the code update both:

$('#my-display').text(yourValue);
$('#my-input').val(yourValue);

You can style the display to the user however you like and don't have to worry about whether or not it "de-activates" the form input.


If you really want it to be an inactive input, you can use the same approach:

<input class="my-input" type="text" disabled />
<input class="my-input" type="hidden" name="my-input" />

Which may even save you a line of code here, since both can now use .val():

$('.my-input').val(yourValue);

Upvotes: 1

Related Questions