Thursday 23 May 2013

JQuery Multiple Checkbox Select/Deselect in the specific column of table

HTML - JQuery code to select and deselect checkboxes in the specific column of table. We can achieve this with very few line of JQuery code. Following are various JQuery methods which we are going use in our code.




» closest()

It begins with the current element and travels up the DOM tree until it finds a match for the supplied selector. The returned jQuery object contains zero or one element

» find()

You can use the find() to search through all the descendants(child, grandchild, great-grandchild…any levels deep) of the matched element

» index()

The index() method returns the index position of specified elements relative to other specified elements

» children()

Get the children of each element in the set of matched elements, optionally filtered by a selector. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while


» HTML Code

<table id="tbl-checkbox">
    <tr><th colspan="4">Select All</th></tr>
    <tr>        
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
        <td><input type="checkbox" class="selectall" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>

» JQuery Code

<script src="js/jquery-1.8.3.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $(".selectall").click(function(){
                     var tbl = $(this).closest("#tbl-checkbox");
            var col_index = $(this).closest("tr").children().index($(this).closest("td")) + 1;
            tbl.find("td:nth-child("+col_index+") input:checkbox").attr("checked",$(this).is(":checked"));
        });        
    });
</script>

No comments:

Post a Comment