63

I'm making a form. And on one input tag is an OnClick event handler, which is opening a popup, where you can choose some stuff, and then it autofills the input tag.

That input tag is also readonly, so only right data will be entered.

This is the code of the input tag:

<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();"  />

But the required attribute isn't working in Chrome. But the field is required.

Does anybody know how I can make it work?

4
  • 3
    required is a attribute new in HTML5 - it is still not supported in all browsers Commented Oct 8, 2012 at 8:22
  • 1
    You should mark your question with the HTML5 tag and Chrome tag Commented Oct 8, 2012 at 8:28
  • 1
    @Muleskinner: It's supported by the stable versions of Firefox, Chrome and Opera: caniuse.com/#search=required Commented Oct 8, 2012 at 8:30
  • 1
    @Blender, thanks for the website, i bookmarked it right away :D Commented Oct 8, 2012 at 8:36

14 Answers 14

120

I had same requirement as yours and I figured out an easy way to do this. If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jQuery this way:

IMPROVED

form the suggestions in comments

<input type="text" class="readonly" autocomplete="off" required />

<script>
    $(".readonly").on('keydown paste focus mousedown', function(e){
        if(e.keyCode != 9) // ignore tab
            e.preventDefault();
    });
</script>

Credits: @Ed Bayiates, @Anton Shchyrov, @appel, @Edhrendal, @Peter Lenjo

ORIGINAL

<input type="text" class="readonly" required />

<script>
    $(".readonly").keydown(function(e){
        e.preventDefault();
    });
</script>
Sign up to request clarification or add additional context in comments.

9 Comments

I also added a paste handler to preventDefault, and the solution was complete!
Good answer, but his blocked ALL keys (included Tab, Left, Right) and not blocked Cut event. I wrote self version :)
Thanks a lot! @Kanak your answer was useful for me.
The fix for number input is adding a 'mousedown' handler.
I added the focus handler to avoid autocomplete and showing the cursor.
|
34

readonly fields cannot have the required attribute, as it's generally assumed that they will already hold some value.

6 Comments

And you don't know an work around? because i want to check it before the form is realy submitted...
@yogi, if you readed the question right, then you saw that i use on OnClick event handler that will popup something that sends an value back...
Well, aside from making some validation to ensure that the value is only one of those you are entering using your JS, there's little you can do. Also, I'd recommend using onfocus, for the use of tabs on your form.
@yogi with a datepicker modal . . .
Yeah datepicker modal is the obvious use case, readonly because it's the only way to stop a mobile device's keyboard popping up unnecessarily.
|
28

Remove readonly and use function

<input type="text" name="name" id="id" required onkeypress="return false;" />

It works as you want.

2 Comments

can not handle delete content when backspace button it clicked.
Is there a way to get rid of the cursor ? maybe focus on some else? is it possible ?
22

Required and readonly don't work together.

But readonly can be replaced with following construction:

     <input     type="text"
                onkeydown="return false;"
                style="caret-color: transparent !important;"                   
                required>

1) onkeydown will stop manipulation with data

2) style="caret-color: transparent !important;" will hide cursor.

3) you can add style="pointer-events: none;" if you don't have any events on your input, but it was not my case, because I used a Month Picker. My Month picker is showing a dialog on click.

Comments

16

This is by design. According to the official HTML5 standard drafts, "if the readonly attribute is specified on an input element, the element is barred from constraint validation." (E.g. its values won't be checked.)

Comments

9

Yes, there is a workaround for this issue. I found it from https://codepen.io/fxm90/pen/zGogwV site.

Solution is as follows.

HTML File

<form>
  <input type="text" value="" required data-readonly />
  <input type="submit" value="Submit" />
</form>

CSS File

input[data-readonly] {
  pointer-events: none;
}

4 Comments

This seems pretty neat. What do you know about the browser support for this css trick?
This doesn't prevent anyone from tabbing into the field and typing some text.
@cyanbeam - Couldn't you add a tabIndex of -1?
I suppose you may. I guess my point is that whatever you do to disable changing the field seems hack-ish and not semantically correct anyway.
8

If anyone wants to do it only from html, This works for me.

<input type="text" onkeydown="event.preventDefault()" required />

1 Comment

A simple solution that simply works. 👍
1

I think this should help.

<form onSubmit="return checkIfInputHasVal()">
    <input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();"  />
</form>

<script>
     function checkIfInputHasVal(){
        if($("#formAfterRederict").val==""){
             alert("formAfterRederict should have a value");
             return false;
        }
     }
</script>

Comments

1

You can do this for your template:

<input required onfocus="unselect($event)" class="disabled">

And this for your js:

unselect(event){
    event.preventDefault();
    event.currentTarget.blur();
}

For a user the input will be disabled and required at the same time, providing you have a css-class for disabled input.

Comments

1

Based on answer @KanakSinghal but without blocked all keys and with blocked cut event

$('.readonly').keydown(function(e) {
  if (e.keyCode === 8 || e.keyCode === 46)  // Backspace & del
    e.preventDefault();
}).on('keypress paste cut', function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="readonly" value="test" />

P.S. Somebody knows as cut event translate to copy event?

Comments

1

Required and readonly don't work together.

Although you can make two inputs like this:

<input id="One" readonly />
<input id="Two" required style="display: none" /> //invisible

And change the value Two to the value that´s inside the input One.

Comments

1

It's the best solution for me. The client can not type anything and must be filled

<input type="text" class="read-only" required>
.read-only {
         pointer-events: none;
 }

Comments

0

I have the same problem, and finally I use this solution (with jQuery):

form.find(':input[required][readonly]').filter(function(){ return this.value === '';})

In addition to the form.checkValidity(), I test the length of the above search somehow this way:

let fcnt = $(form)
    .find(':input[required][readonly]')
    .filter(function() { return this.value === '';})
    .length;

if (form.checkValidity() && !fcnt) {
   form.submit();
}

Comments

-1

  function validateForm() {
    var x = document.forms["myForm"]["test2"].value;
    if (x == "") {
      alert("Name missing!!");
      return false;
    }
  }
  <form class="form-horizontal" onsubmit="return validateForm()" name="myForm" action="" method="POST">
   <input type="text"  name="test1">
    <input type="text" disabled name="test2">
    <button type="submit">Submit</button>
</form>

1 Comment

Some explanation to support your answer please. Code only answers are not very educational.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.