Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Web
Expertise: Intermediate
Jun 2, 1999

Validate a Drop-Down List on a Form

The easiest way to make ensure that a user picks a value from a dropdown list is to add a value to the top of the list that isn't really a valid choice, but a prompt instead. Something like "select one" should do. Make sure to set the value of this dummy item to a known value that won't conflict with the real choices in your list. Zero (0) and negative 1 (-1) are usually a safe bet. Then before you submit the form, double check and make sure that the selectedIndex property of the select object isn't set to the dummy value. If it is, prompt the user to make a selection, otherwise use the form's submit() method to submit the form.
 
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validateForm(objForm)
{
	var returnStatus = 1;

	if (objForm.Make.selectedIndex == 0) {
		alert("Please select a car make");
		returnStatus = 0;
	};

	if (returnStatus) {
		objForm.submit();
	}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<FORM ACTION="test.asp" NAME="testform">
<SELECT NAME="Make">
	<OPTION VALUE="0" SELECTED>Select One</OPTION>
	<OPTION VALUE="1">Ford</OPTION>
	<OPTION VALUE="2">Chevy</OPTION>
	<OPTION VALUE="3">Pontiac</OPTION>
	<OPTION VALUE="4">Dodge</OPTION>
</SELECT>	
<INPUT TYPE="BUTTON" VALUE="Send form"
onClick="validateForm(document.testform)">
</FORM>
</BODY>
</HTML>
Boris Feldman
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap