HTML <select> required Attribute

HTMLWeb DevelopmentFront End Technology

The required attribute of the <select> element is to let users know that the <select> drop-down is required and need to be submitted before the form is submitted. If you won’t select the value from the drop-down and try to submit the form, it won’t submit and a warning would be visible on the web page itself. The required attribute introduced in HTML5.

Following is the syntax−

<select required>

Let us now see an example to implement the required attribute of the <select> element−

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<h1>Candidate Profile</h1>
<p>Following are the details to be submitted by the candidate:</p>
<h2>Educational Qualification</h2>
<form action="">
<section>
<h3>Graduation</h3>
<select required>
   <option value="">None</option>
   <option value="bca">BCA</option>
   <option value="bcom">B.COM</option>
   <option value="btech">B.TECH</option>
</select>
</section>
<section>
<h3>Postgraduation</h3>
<select>
   <option value="mca">MCA</option>
   <option value="mcom">M.COM</option>
   <option value="mtech">M.TECH</option>
   <option value="msc">M.Sc</option>
</select>
</section><br>
<input type="submit" value="Next">
</form>
</body>
</html>

This will produce the following output. We haven’t selected an item from the drop-down list set as required, therefore the following warning would be visible−

In the above example, we have set two drop-down lists using <select>−

<section>
<h3>Graduation</h3>
<select required>
   <option value="">None</option>
   <option value="bca">BCA</option>
   <option value="bcom">B.COM</option>
   <option value="btech">B.TECH</option>
</select>
</section>
<section>
<h3>Postgraduation</h3>
<select>
   <option value="mca">MCA</option>
   <option value="mcom">M.COM</option>
   <option value="mtech">M.TECH</option>
   <option value="msc">M.Sc</option>
</select>
</section>

We have set one of them to be filled compulsory by the users using the required attribute, else the form won’t submit−

<section>
<h3>Graduation</h3>
<select required>
   <option value="">None</option>
   <option value="bca">BCA</option>
   <option value="bcom">B.COM</option>
   <option value="btech">B.TECH</option>
</select>
</section>
raja
Published on 19-Jun-2019 09:03:00
Advertisements