Skip to content

Instantly share code, notes, and snippets.

@Mauryashubham
Created August 23, 2017 07:49
Show Gist options
  • Save Mauryashubham/6a1a5d8ebf75e5fefcb516b241a290db to your computer and use it in GitHub Desktop.
Save Mauryashubham/6a1a5d8ebf75e5fefcb516b241a290db to your computer and use it in GitHub Desktop.
HTML select required Attribute
/**
@author : Shubham Maurya,
Email id : maurya.shubham5@gmail.com
**/
Hi all , Welcome to shubhammaurya.com , Today we are going to discuss ,
How to Make Select tag required by using two methods.
1.By Simple method i.e required tag.
2.By using javascript.
WITH USING JAVASCRIPT
So, To start first make a file in notepad and save it as index.php and paste the below code.
<?php
if (isset($_POST['submit']))
{
$se = $_POST['course'];
echo "<br>selected course is : ".$se;
}
?>
<html>
<head>
<script type="text/JavaScript">
function validate()
{
if( document.form1.course.value == "0" )
{
alert( "Please select Course" );
return false;
}
}
</script>
</head>
<body>
<form method="post" name="form1" onsubmit="return validate(this);" >
<select name="course" >
<option value="0" selected="" disabled="">Courses</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="BA">BA</option>
<option value="B.COM">B.COM</option>
<option value="B.TECH">B.TECH</option>
</select>
<input type="submit" name="submit" value="try it">
</form>
</body>
</html>
WITH USING SIMPLE METHOD
So, To start first make a file in notepad and save it as index_new.php and paste the below code.
<?php
if (isset($_POST['submit1']))
{
$se = $_POST['course'];
echo "<br>selected course is : ".$se;
}
?>
<html>
<body>
<form method="post" required >
<select name="course" >
<option value="0" selected="" disabled="">Courses</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="BA">BA</option>
<option value="B.COM">B.COM</option>
<option value="B.TECH">B.TECH</option>
</select>
<input type="submit" name="submit1" value="try it">
</form>
</body>
</html>
Note : Sometime the 'required' method doesnot work.So make sure to check the 'required' method in your code. If 'required' method doesn't work. Then Use javascript method. It will work 100%.
For More VISIT My website : http://shubhammaurya.com
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment