Thursday, November 12, 2009

Working with JQuery and list boxes

Code (read comments):

<script type="text/javascript" src="">
<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.
//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.
toAppendHtml += $(this).text() +" : "+$(this).val()+"<br/>";
//finally put everything in there as html content to itemsSelected.
Alternatively you can use ExternalFunction. The external function should have one parameter "e" called the event object.
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.
<style type="text/css">
width: 100px;
height: 200px;
<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>
<div>total items selected : <span id="itemsCount">0</span></div>
<span>Selected Items are </span>
<div id="itemsSelected"/>

No comments: