Zerotoinfinity
Zerotoinfinity

Reputation: 6530

Select/unselect all checkboxes in a list

I have a list (id: lstName), I want to have a link with the list box (i.e. select all) when the user clicks on the select all link, all items in the list will be selected and at the same time the text for the link will be changed from "select all" to "unselect all", and vice versa.

As I have three other listbox in my page, is there any way I can have a general function in which I can pass the listbox id and link id and it will do the above task=

Please help, I have no idea about javascript and jquery.

Upvotes: 0

Views: 1116

Answers (2)

Shardiwal
Shardiwal

Reputation: 16

You can do something like this

<div>
    <button>Toggle</button>
    <a href="javascript:check_uncheck(1)">Select All</a>
    <a href="javascript:check_uncheck(0)" style="display:none;">Unselect All</a>
</div>

<input type="checkbox" class="selection">
<input type="checkbox" class="selection">
<input type="checkbox" class="selection">

<script>
$("button").click( function(){
    $("a").toggle();
});

function check_uncheck(is_check){
    $.each( $('.selection'), function ( index, value ) { 
        if ( is_check ) { 
            $(value).attr('checked', true); 
        } 
        else{ 
            $(value).attr('checked', false); 
        } 
    });
}
</script>

Upvotes: 0

Christopher Marshall
Christopher Marshall

Reputation: 10736

$(".select-all").click(function() {
            $('#IstName select option').prop('selected',true);
            $(this).addClass("selected");
            $(this).text("Unselect All");
    }) ;
 $(".selected").click(function() {
            $('#IstName select option').prop('selected',false);
            $(this).removeClass("selected");
            $(this).text("Select All");
    }) ;

That should work.

Upvotes: 1

Related Questions