1

Is there a css or html only way to prevent a user from typing in an input field?

I want to dynamically add stuff and remove stuff etc to an input field but I don't want the user to be able to edit it and using the disable attribute on the html tag prevents me from doing what I want.

pourmesomecode
  • 4,108
  • 10
  • 46
  • 87

6 Answers6

4

You can use readonly or disabled attribute.

The drawback to using disabled is that the value of the disabled element won't be submitted when the form is.

You'll likely want readonly. Which can easily be styled to look like a disabled element.

document.getElementById('test').value = 'Hello World!';
[readonly] {
  border: 1px solid #ccc;
  background-color: #eee;
}
<input type="text" id="test" name="test" readonly>
hungerstar
  • 21,206
  • 6
  • 50
  • 59
1

You can use the attribute readonly - read about it here

1

Yep, you can just set the input element's disabled property to true. That will prevent the user from modifying its contents, but you can do what you like with it by using Javascript to modify its value property.

DRAB
  • 445
  • 2
  • 10
1

add readonly to it

<input type="text" value="Hello" readonly />
Rudi Urbanek
  • 1,935
  • 1
  • 12
  • 15
0

Uhm.....

<input type="text" name="myInput" value="Whatever" readonly="readonly" />

More here: What is the correct readonly attribute syntax for input text elements?

Community
  • 1
  • 1
Scott
  • 21,475
  • 8
  • 43
  • 55
0

You can fake the disabled effect using CSS.

pointer-events:none;

You might also want to change colors etc.

CSS is not meant to change the behavior of form elements. It's meant to change their style only. Hiding a text field doesn't mean the text field is no longer there or that the browser won't send its data when you submit the form. All it does is hide it from the user's eyes.

To actually disable your fields, you must use the disabled attribute in HTML or the disabled DOM property in JavaScript.

OR JQUERY

$('#fieldname').attr('disabled', 'disabled'); //Disable
$('#fieldname').removeAttr('disabled'); //Enable
Stivan
  • 1,128
  • 1
  • 15
  • 24
  • 1
    I could use tab / shift+tab via keyboard and enter text in the input field – AA2992 Sep 08 '16 at 15:23
  • @AnkithAmtange Which one of the methods above did you do this on? – Stivan Sep 08 '16 at 15:26
  • `pointer events: none.` ha! neat trick but I can tab and then also use space bar to activate checkbox/radio – AA2992 Sep 08 '16 at 15:27
  • 1
    @AnkithAmtange Yeah when he mentioned he wanted to do this using css that's the only thing that came to mind. Thanks for bringing that up though :) – Stivan Sep 08 '16 at 15:29