Working with JQuery and list boxes

12 Nov 2009

Code (read comments):

<html> 
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
/*
when the document is ready (after all the HTML page is loaded, this shall be executed)
we attach the event handlers.
*/
$(document).ready(function(){ attachEventHandlers(); });
function attachEventHandlers(){
/*
In this method we attach the function(){} to the change event on all the <select> items.
The code inside the function(){} shall be executed when item selections are changed on the select box.
*/
$("select").change(function(){
//using "this" to access the current listbox. the jQuery wrapper would be $(this)
var selectedItems = $(":selected",this);
$("#itemsCount").text(selectedItems.length); //set the items selected count.
var toAppendHtml = ""; //lets store the html that we shall put inside the itemsSelected element.
//for each selected item we add a new line with selected item's text and value to the toAppendHtml.
selectedItems.each(function(){
toAppendHtml += $(this).text() +" : "+$(this).val()+"<br/>";
});
//finally put everything in there as html content to itemsSelected.
$("#itemsSelected").html(toAppendHtml);
});
/*
Alternatively you can use ExternalFunction. The external function should have one parameter "e" called the event object.
$("select").click(ExternalFunction);
*/
}
/*
function ExternalFunction(e)
{
//now within this function, the element which raised the event can be accessed using "this", or "e.currentTarget".
//So the statement "this == e.currentTarget" will always be true.
alert($(":selected",this).length);
}
*/
</script>
<style type="text/css">
select{
width: 100px;
height: 200px;
}
</style>
</head>
<body>
<select name="items" id="items" multiple="true">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="4">Item 4</option>
<option value="5">Item 5</option>
<option value="6">Item 6</option>
<option value="7">Item 7</option>
</select>
<p/>
<div>total items selected : <span id="itemsCount">0</span></div>
<span>Selected Items are </span>
<div id="itemsSelected"/>
</body>
</html>