Can I apply the required attribute to ` element does not work or can't apply with CSS `:invalid`. – vee Mar 31 '22 at 07:25

2
<form action="">

<select required>

  <option selected disabled value="">choose</option>
  <option value="red">red</option>
  <option value="yellow">yellow</option>
  <option value="green">green</option>
  <option value="grey">grey</option>

</select>
<input type="submit">
</form>
yatou
  • 57
  • 1
2

try this, this gonna work, I have tried this and this works.

<!DOCTYPE html>
<html>
<body>

<form action="#">
<select required>
  <option value="">None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

</body>
</html>
sayyed tabrez
  • 116
  • 1
  • 1
  • 11
1

Make the value of first item of selection box to blank.

So when every you post the FORM you get blank value and using this way you would know that user hasn't selected anything from dropdown.

<select name="user_role" required>
    <option value="">-Select-</option>
    <option value="User">User</option>
    <option value="Admin">Admin</option>
</select>
Alok Patel
  • 7,842
  • 5
  • 31
  • 47
1

first you have to assign blank value in first option. i.e. Select here.than only required will work.

ayush
  • 19
  • 2
1

Works perfectly fine if the first option's value is null. Explanation : The HTML5 will read a null value on button submit. If not null (value attribute), the selected value is assumed not to be null hence the validation would have worked i.e by checking if there's been data in the option tag. Therefore it will not produce the validation method. However, i guess the other side becomes clear, if the value attribute is set to null ie (value = "" ), HTML5 will detect an empty value on the first or rather the default selected option thus giving out the validation message. Thanks for asking. Happy to help. Glad to know if i did.

-1

In html5 you can do using the full expression:

<select required="required">

I don't know why the short expression doesn't work, but try this one. It will solve.

-4

Try this

<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>
-5

You can do it also dynamically with JQuery

Set required

$("#select1").attr('required', 'required');

Remove required

$("#select1").removeAttr('required');
james.garriss
  • 12,959
  • 7
  • 83
  • 96
mdelafuq
  • 130
  • 3
  • 12