2

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.

2
  • 1
    Please provide your current code. Commented Sep 8, 2016 at 15:14
  • @YashJain I only didn't include my code since it was just one input field :) Commented Sep 8, 2016 at 15:20

6 Answers 6

5

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>

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the attribute readonly - read about it here

Comments

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.

Comments

1

add readonly to it

<input type="text" value="Hello" readonly />

1 Comment

That's not the proper way to close input tags -- they are self-closing.
0

Uhm.....

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

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

Comments

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

4 Comments

I could use tab / shift+tab via keyboard and enter text in the input field
@AnkithAmtange Which one of the methods above did you do this on?
pointer events: none. ha! neat trick but I can tab and then also use space bar to activate checkbox/radio
@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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.