Can I apply the required attribute to <select> fields in HTML?
Asked Answered
C

13

315

How can I check if a user has selected something from a <select> field in HTML?

I see <select> doesn't support the new required attribute... do I have to use JavaScript then? Or is there something I’m missing? :/

Chur answered 18/5, 2011 at 17:32 Comment(2)
If you're interested in any level of cross-browser compatibility, you'll probably have to use JavaScript. The attribute you want is selectedIndex.Virgilvirgilia
Per the current editor's draft of the HTML5 spec (6 Aug 2011), the select element does have a required attribute. "The required attribute is a boolean attribute. When specified, the user will be required to select a value before submitting the form." dev.w3.org/html5/spec/Overview.html#the-select-elementBelly
U
582

Mandatory: Have the first value empty - required works on empty values

Prerequisites: correct html5 DOCTYPE and a named input field

<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>

As per the documentation (the listing and bold is mine)

The required attribute is a boolean attribute.
When specified, the user will be required to select a value before submitting the form.

If a select element

  • has a required attribute specified,
  • does not have a multiple attribute specified,
  • and has a display size of 1 (do not have SIZE=2 or more - omit it if not needed);
  • and if the value of the first option element in the select element's list of options (if any) is the empty string (i.e. present as value=""),
  • and that option element's parent node is the select element (and not an optgroup element),

then that option is the select element's placeholder label option.

Ulane answered 18/5, 2011 at 17:49 Comment(19)
Also, so that the user can't select the non-option once it has been selected: <option selected="selected" disabled="disabled" value="">Please Select</option>Following
@CoolAJ86 Works in Chrome 23, Firefox 16 and IE 10 well.Andorra
@Ulane I know adding aria-required="required" on input fields does help improve support, although I'm unsure about on selects. Thoughts?Thuythuya
Interesting, I have not used Aria yet. Did you try? Here is more info developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/…Ulane
The paraphrasing of the documentation is very helpful; thanksGoebbels
You can use the :valid css selector to apply a custom style to a select element depending on if the empty value is selected.Punak
what does "display size of 1" mean?Hypochlorite
Actually, it's 0 developer.mozilla.org/en-US/docs/Web/HTML/Element/… and THAT was sucking my dayHypochlorite
Ah yes - do NOT specify size!Ulane
Per the last comment, should this answer be edited to remove the display size 1 requirement?Shreve
That is the default - so perhaps I need to say: do NOT specify size unless it it 1 in which case omit itUlane
A nice trick is to remove the placeholder option on focus of the select. Of course, this would depend greatly on the nature of the form.Now
Notice that simply omitting the value attribute does not work, you have to include value="".Hypodermic
And if the value of the first option element is the empty string,Ulane
How can I get an error message from this? Like other filed (input) provided.Chanticleer
@rajibkarmaker add the attribute required and the browser generates the error message for you - see developer.mozilla.org/en-US/docs/Web/HTML/Element/input - your doctype has to be html5 compliantUlane
Clarification on the disabled attribute for the placeholder option: works fine in Safari, but fails in Firefox 74 (the second option element is selected when the page is shown.)Subantarctic
@Subantarctic You are referring to the comment where I stated That does not make sense... Also it will not work on several browsers Ulane
Yes, exactly. I just think it would make sense to use, as you could prevent the user from selecting that item. But alas, it doesn't work (consistently.)Subantarctic
S
15

The <select> element does support the required attribute, as per the spec:

Which browser doesn’t honour this?

(Of course, you have to validate on the server anyway, as you can’t guarantee that users will have JavaScript enabled.)

Subscapular answered 18/5, 2011 at 18:27 Comment(4)
I am sure he just needed a value="" on the first entry - if there is no value attribute or a value on all options the required fail to trigger because the select returns an actual valueUlane
@mplungjan: ah, gotcha — well-spotted.Subscapular
@PaulD.Waite Can we still not guarantee that users will have Javascript enabled? I've only been in web development about 2 years now and I've never run into that problem.Aerograph
@user137717: It’s the web. You can’t guarantee anything. You can, of course, decide that it’s not worth catering for.Subscapular
L
13

Yes, it's working:

<select name="somename" required>
     <option value="">Please select</option>
     <option value="one">One</option>
</select>

you have to keep first option blank.

Layamon answered 1/5, 2016 at 11:48 Comment(0)
B
7

You can use the selected attribute for the option element to select a choice by default. You can use the required attribute for the select element to ensure that the user selects something.

In Javascript, you can check the selectedIndex property to get the index of the selected option, or you can check the value property to get the value of the selected option.

According to the HTML5 spec, selectedIndex "returns the index of the first selected item, if any, or −1 if there is no selected item. And value "returns the value of the first selected item, if any, or the empty string if there is no selected item." So if selectedIndex = -1, then you know they haven't selected anything.

<button type="button" onclick="displaySelection()">What did I pick?</button>
<script>
    function displaySelection()
    {
        var mySelect = document.getElementById("someSelectElement");
        var mySelection = mySelect.selectedIndex;
        alert(mySelection);
    }
</script>
Belly answered 9/8, 2011 at 18:50 Comment(2)
@Apostle - Please stop trying to change this answer via edits. If you believe it is incorrect, feel free to leave your own answer.Vaunt
@BradLarson At first I did not quite understand: the code is not a complete solution to the problem in this question or is an explanatory example to the last paragraph of this answer. Probably second in this case. I think better to organize this code as a snippet and show the result -1. Sorry, I didn't clarify in comments first.Spies
P
5

You need to set the value attribute of option to the empty string:

<select name="status" required>
    <option selected disabled value="">what's your status?</option>
    <option value="code">coding</option>
    <option value="sleep">sleeping</option>
</select>

select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input -> raising the required message.


w3schools

The value attribute specifies the value to be sent to a server when a form is submitted.

Example

Pirouette answered 12/1, 2018 at 0:33 Comment(1)
This is the most perfect answer IF you try to apply required attribute, apply :invalid CSS pseudo class because it work in all browsers! The other answer that have no required and selected attributes in <option> element with required attribute in <select> element does not work or can't apply with CSS :invalid.Barela
S
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>
Selenography answered 22/7, 2014 at 13:32 Comment(2)
This answer merely repeats a previous example with no additional explanation.Belly
Please add some explanation to your answer such that others can learn from itAuroraauroral
C
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>
Cumine answered 16/3, 2018 at 10:2 Comment(1)
Please add some explanation to your answer such that others can learn from itAuroraauroral
L
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>
Loggerhead answered 22/7, 2016 at 6:37 Comment(0)
A
1

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

Actiniform answered 17/7, 2017 at 6:5 Comment(0)
E
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.

Expedient answered 11/5, 2020 at 13:16 Comment(0)
H
-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.

Hartz answered 11/1, 2016 at 3:9 Comment(0)
E
-4

Try this

<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>
Endblown answered 17/4, 2013 at 7:1 Comment(1)
Please add some explanation to your answer such that others can learn from itAuroraauroral
E
-5

You can do it also dynamically with JQuery

Set required

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

Remove required

$("#select1").removeAttr('required');
Evenings answered 12/5, 2014 at 15:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.