Monday 9 February 2015

Validate Multiple-Select List Box Using JavaScript

Hi Guys,
In this post we are going to see how to Validate Multiple-Select list box using JavaScript.

Recently i came to worked on validating Multiple-Select List box. For e.g i have a 5 items in my list box, the user need to select maximum of 2 items not more than that. For this i need to write a JS code for validating Multiple-Select list box.

Lets see how to validate the list box using JavaScript.
Index.jsp

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function get(){

var list=document.getElementById("demo");
console.log(list);

var selectd_items=0;

for(var i=0;i<list.length;i++){

if(list[i].selected){
console.log(list[i].selected);

selectd_items++;

}

}

if(selectd_items==0 || selectd_items==1){

alert("Please select at least two item");

}else if(selectd_items>2){

alert("Don't select more than two items");

}

}
</script>
</head>
<body>
<form>
<select id="demo" multiple="multiple">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
<input type="button" value="Submit" onclick="get()">
</form>
</body>
</html>


Inside script i wrote a function called get() which should calls from button onclick and it gets all the list items from Multiple-Select box, Once i get the items iterate the list and store the selected items in a variable selectd_items. After getting the items check whether the user selected maximum of 2 items, not more than that.

That's all folks.. Hope You got some ideas from this post..


No comments:

Post a Comment