Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML make <option> invalid

I have the following piece of code in a contact form for a site I am designing:

<select id="Category" name="Category">
    <option value="0" selected="selected" disabled>Category</option>
    <option value="1">General Info</option>
    <option value="2">Booking</option>
    <option value="3">Auditions</option>
</select>

I would like set the menu such that the user cannot leave category as the selected option. Is there any way to do this with HTML? If not, how would I do it with JavaScript?

Thank you

like image 834
Ryan Avatar asked Apr 28 '15 19:04

Ryan


People also ask

How do I make a form element invalid?

field. setCustomValidity("Invalid field."); will make the field invalid.

What is select invalid?

The :invalid selector selects form elements with a value that does not validate according to the element's settings.

What is invalid in HTML?

Definition and Usage The oninvalid event occurs when a submittable <input> element is invalid. For example, the input field is invalid if the required attribute is set and the field is empty (the required attribute specifies that the input field must be filled out before submitting the form).


1 Answers

When the user click on any option, he can´t return the first one back. But he can submit form without change, then you need to validate via JS.

It's quite simple,

function validate() {
    var select = document.getElementById('Category');
    return !select.value == 0;
}

And the form in HTML:

<form onsubmit="return validate()">...</form>
like image 54
pavel Avatar answered Nov 07 '22 07:11

pavel