Wednesday, August 8, 2012

jQuery Multi select box


Found a jQuery snippet for  Multi select box.

 HTML :

<select multiple="multiple">
<option value="foo">foo</option>
<option value="bar">bar</option>
<option value="baz">baz</option>
</select>

<div id="target">target</div>


 Jquery 1.4 

var target = $("#target");

$("select")
    .multiselect()
    .bind("multiselectclick multiselectcheckall multiselectuncheckall", function( event, ui ){
        
        // the getChecked method returns an array of DOM elements.
        // map over them to create a new array of just the values.
        // you could also do this by maintaining your own array of
        // checked/unchecked values, but this is just as easy.
        var checkedValues = $.map($(this).multiselect("getChecked"), function( input ){
            return input.value;
        });
        
        // update the target based on how many are checked
        target.html(
            checkedValues.length
                ? checkedValues.join(', ')
                : 'Please select a checkbox'
        );
    })
    .triggerHandler("multiselectclick"); // trigger above logic when page first loads


CSS:

#target { padding: 5px; border: 1px solid #000; width:200px; float:right }

JS Fiddle link :  http://jsfiddle.net/ehynds/rTjkr/

No comments:

Post a Comment