Multiple selection of Drop down listbox onChange

We have how to read selected item of a drop down listbox. Now we will learn how to read date when we use multiple selection in a dropdown list box. Here is the code to read the data. We will get all the options of the list box in an array. So total number of elements of an array can be found out by using length property.
s1.length
To display the element we will use for loop.
<script type="text/javascript"> 
function show_date(){
var str='';

for (i=0;i<s1.length;i++) { 
if(s1[i].selected){
str +=s1[i].value + "<br >"; 
}
} 

document.getElementById("msg3").innerHTML=str;
return true;
}
</script>
Note that inside the for loop we are using one if condition to found out which are the elements selected. To do this we have used s1[i].selected. This will return true if the options is selected. Then we will add to our string by using s1.value property.

Demo of reading Multiple selection

Here is the complete code.
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<html>
<head>
<title>Demo of onChange of a listbox to trigger a JavaScript function to read selected option</title>
<META NAME="DESCRIPTION" CONTENT="demo of Reading selected option of a list box by using onChange event of a list box in JavaScript">
<link rel="stylesheet" href="../images/all11.css" type="text/css">
<script type="text/javascript"> 
function show_date(){
var str='';
for (i=0;i<s1.length;i++) { 
if(s1[i].selected){
str +=s1[i].value + "<br >"; 
}
} 
document.getElementById("msg3").innerHTML=str;
return true;
}
</script>

</head>
<body>

<select id=s1 name=no_year onChange="show_date()"; multiple size=4><option value=Jan>January</option>
<option value=February>February</option>
<option value=March>March</option>
<option value=April>April</option>
<option value=June>June</option>
<option value=Jul>July</option>
<option value=Auguest>Auguest</option>
<option value=September>Septembr</option>
<option value=October>October</option>
<option value=November>November</option>
<option value=December>December</option>
</select>
<div id='msg3'><br><br></div>

</body>
</html>

Selection option of listbox


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer