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: Advanced
Feb 18, 2000

Prevent Default Value Selections in a List Box

A pretty typical scenario is a drop-down list box with a standard default selection that instructs the user to choose an option. It is enclosed in <FORM> tags, which the user will submit and looks something like this:

 
<FORM NAME="mainform" ACTION="//yourserver/takeanswer.asp" 
METHOD="POST">
<SELECT NAME="TriviaAnswer">
<OPTION VALUE="0" SELECTED>Baseball Player Answer</OPTION>
<OPTION VALUE="1">Ken Griffey</OPTION>
<OPTION VALUE="2">Ron Dibble</OPTION>
<OPTION VALUE="3">Ty Cobb</OPTION>
<OPTION VALUE="4">Hank Aaron</OPTION>
<OPTION VALUE="5">Marge Schott</OPTION>
</SELECT>
<INPUT TYPE="SUBMIT" Value="Submit Answer">
</FORM>

However, you don't want the user picking the default response of "Baseball Player Answer". A good way to prevent this selection from happening is to handle the submit yourself and check the value of the SELECT box. You change the FORM tag onsubmit event so the new tag looks like this:

 
<FORM NAME="triviaform" ACTION="//yourserver/takeanswer.asp" 
onsubmit="checkvalue();" METHOD="POST">

Note that when the onsubmit event is fired it will now attempt to call the checkvalue function when the "Submit Answer" button is pressed. You define this short JavaScript routine on the client-side like this:

 
<SCRIPT>
function checkvalue() {
if (triviaform.TriviaAnswer.options[0].selected) {
alert('You must enter your response.');
event.returnValue=false;
}
}
</SCRIPT>

If the default option at index 0 is selected, you pop up a message and cancel the request. This type of simple client-side validation is useful because it can prevent unnecessary roundtrips to the server.

Bill Pitzer
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date