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
Jul 9, 1999

Count How Many Items Have Been Selected

The SELECT element includes an options array that is accessible from JavaScript. You can use a loop to iterate through this array and count how many choices the user has selected. For each one, the option's selected property will be true. The countSelect() function in this code does just that and returns the number of selected items. You can use the result of this function to make sure that the user has made at least one selection.

 
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
// check a string to make sure it includes at least one number
function countSelect(ctrl) {
	var i;
	var numSelected = 0;

	for (i = 0; i < ctrl.options.length; i++) {
		if (ctrl.options[i].selected) {
			numSelected++;
		}
	}

	return numSelected;
}
// -->
</SCRIPT>
</HEAD>
<BODY>

<FORM>
<SELECT NAME="city" MULTIPLE>
<OPTION>Austin</OPTION>
<OPTION>Boston</OPTION>
<OPTION>New York</OPTION>
<OPTION>San Francisco</OPTION>
<OPTION>Seattle</OPTION>
</SELECT>
<BR>
<INPUT TYPE="BUTTON" VALUE="Go!" 
onClick="alert((countSelect(this.form.city) > 0))">
</FORM>

</BODY>
</HTML>
Boris Feldman
 
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