Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why `readonly`, `disabled` and `required` in same input field text is not working properly?

I am using readonly, disabled and required property of input text field like this:

<input type="text" id="visitDate" name="visitdate" readonly="readonly" disabled="disabled" required="required" />

My problem is that two of three property i.e. disabled and readonly are working properly but required is not working. Submit button allows to submit even it is empty. But if I remove readonly form can't be submitted empty.

I use

readonly because I am using date picker and user are not allowed to input date manual.

disabled because I want this input field disable at the beginning

required because use must select date from date picker so that date will not be empty.

like image 292
Krity Shrestha Avatar asked Mar 09 '23 19:03

Krity Shrestha


1 Answers

What actually happen is that by default(HTML Implementation of Validations), the validation in HTML will not fire if a field is read-only or disable.

The Reason to it is simple. If the field is empty with attribute disabled or read-only, and a required validation is applied, the form could not be valid at any time.

It seems like there is no direct and ethical solution to this, but the indirect solution could be:

i) Handeling key-up/key-down events so that input could not be added.

jQuery Code:

$('input').keypress(function(e) {
    e.preventDefault();
});

ii) For disabling control, I would suggest not to add the datepicker to the element until you want. Later, you can add it using JS when needed(In your case, register datepicker on select list changed event).

Also, you can use Enable and Disable jQuery events if you are using jQuery UI Datepickers like below:

$("#txtSearch").datepicker("enable");
$("#txtSearch").datepicker("disable");

For further reading, you can have a look to this link. This is a discussion on Bootstrap validation, but it applies to pure HTML too.

Hope, this will help.

like image 158
Spidi's Web Avatar answered Apr 06 '23 14:04

Spidi's Web