[javascript] Can I apply the required attribute to <select> fields in HTML5?

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

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

This question is related to javascript html select required ui-select2

The answer is


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.


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.


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>

<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>

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>

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


You can do it also dynamically with JQuery

Set required

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

Remove required

$("#select1").removeAttr('required');

Try this

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

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


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>

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.


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.)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to required

lvalue required as left operand of assignment error when using C++ Angular is automatically adding 'ng-invalid' class on 'required' fields Explain why constructor inject is better than other options HTML5 required attribute seems not working What is the difference between required and ng-required? Is the 'as' keyword required in Oracle to define an alias? How to use the "required" attribute with a "radio" input field Can I apply the required attribute to <select> fields in HTML5?

Examples related to ui-select2

How to get Selected Text from select2 when using <input> How do I change selected value of select2 dropdown with JqGrid? Update select2 data without rebuilding the control set the width of select2 input (through Angular-ui directive) Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio? Can I apply the required attribute to <select> fields in HTML5? jQuery UI tabs. How to select a tab based on its id not based on index How To Get Selected Value From UIPickerView UIButton: set image for selected-highlighted state How can I pass selected row to commandLink inside dataTable or ui:repeat?