JavaScript validate select tag


 

JavaScript validate select tag

In this tutorial, you will learn how to validate html select tag.

In this tutorial, you will learn how to validate html select tag.

JavaScript validate select tag

In this tutorial, you will learn how to validate html select tag. Here, we have used two select tags to select numbers in order to calculate addition of two numbers. If the user does not select any of the select box, an error message will get displayed.

Example:

<html>
<script language = "Javascript">
function validate(){
if(document.form.n1.selectedIndex==""){
alert ( "Please select first number!" );
return false;
}
if(document.form.n2.selectedIndex==""){
alert ( "Please select second number!" );
return false;
}
var v1=document.form.n1.value;
var v2=document.form.n2.value;
var sum=parseInt(v1)+parseInt(v2);
alert("Sum of two numbers: "+sum);
return true;
}
</script>
<form name="form" method="post" onSubmit="return validate()">
<pre>
Select Number1 <select name="n1">
<option value="Select">Select</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
Select Number2 <select name="n2">
<option value="Select">Select</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
<option value="100">100</option>
</select>

<input type="submit" name="Submit" value="Submit">
</pre>
</form>
</html>

Ads