JavaScript Data Validation Multi-selection List Box


This post is a continuation of the previous post that discussed how to implement a drop-down box on your website using JavaScript to change the background color of your web page. The same pattern could be used to change other elements on your web page.

Extending that example, we will now ask the user to select as many as they wish from a list of things that we will then print back out to the website. This blog post was modified from a discussion in the book: JavaScript and AJAX for Dummies, Chapter 7: Getting Valid Input.

Multiple Selections




The HTML code for this drop-down list box and its title is shown below.

<h4>Multiple Selections</h4>
<form>
<fieldset>
<label>
Select the language(s) you know.
(ctrl-click to select multiple lines)
</label>
<select id = "selLanguage"
multiple = "multiple"
size = "7">
<option value = "XHTML">XHTML</option>
<option value = "CSS">CSS</option>
<option value = "JavaScript">JavaScript</option>
<option value = "PHP">PHP</option>
<option value = "MySQL">MySQL</option>
<option value = "Java">Java</option>
<option value = "VB.NET">VB.NET</option>
</select>
<button type = "button"
onclick = "showChoicesJSValidation()">
Submit
</button>
</fieldset>
</form>
<div id="outputLanguages">
</div>

Our JavaScript code is shown below.

function showChoicesJSValidation(){
	//retrieve data
	var selLanguage = document.getElementById("selLanguage");
	//set up output string
	var result = "<h2>Your Languages<\/h2>";
	result += "<ul> \n";
	//step through options
	for (i = 0; i < selLanguage.length; i++){
		//examine current option
		currentOption = selLanguage[i];
		//print it if it has been selected
		if (currentOption.selected == true){
			result += " <li>" + currentOption.value + "<\/li> \n";
		} 
	} 
	//finish off the list and print it out
	result += "<\/ul> \n";
	langoutput = document.getElementById("outputLanguages");
	langoutput.innerHTML = result;
} 

The JavaScript code requires a bit of explanation. First, at the end of the code we assign a string to the innerHTML of the output. Before doing that we build the string by first realizing that we are working with an array. We can go through the array to get the list of items that the user selected, inserting the appropriate HTML elements along the way.

Leave a comment

Your email address will not be published. Required fields are marked *