Need to understand jquery code

Hi,

I am new bie and need to understand below jquery code, i found this code from web source,
why we writing this:
(1) this.checked
(2) .length==$(‘.case:checked’).length

can any 1 explain me above 2 points to understand the code…

<table border="1">
<tr>
    <th><input type="checkbox" id="selectall"/></th>
    <th>Cell phone</th>
    <th>Rating</th>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
    <td>BlackBerry Bold 9650</td>
    <td>2/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
    <td>Samsung Galaxy</td>
    <td>3.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="3"/></td>
    <td>Droid X</td>
    <td>4.5/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="4"/></td>
    <td>HTC Desire</td>
    <td>3/5</td>
</tr>
<tr>
    <td align="center"><input type="checkbox" class="case" name="case" value="5"/></td>
    <td>Apple iPhone 4</td>
    <td>5/5</td>
</tr>
</table>

<SCRIPT>       
        $(function(){
            $('#selectall').click(function(){
                $('.case').attr('checked', this.checked);
            });
            $('.case').click(function(){
                if($('.case').length==$('.case:checked').length){
                    $('#selectall').attr('checked','checked');
                }else{
                    $('#selectall').removeAttr('checked');
                }
            });
        });    
</SCRIPT>

Hi,

My JS is pretty basic but it goes something like this :smile:

That will give a result of either ‘true’ or ‘false’ depending on whether the input that was clicked was checked or not. (‘this’ refers to the input that was clicked and ‘checked’ refers to its checked status)

.length is counting how many items there are called .case and then compares it to how many of the same items are in the ‘checked’ state.

You need to use .prop instead of .attr here to make this work properly:

$(function(){
            $('#selectall').click(function(){
                $('.case').prop('checked', this.checked);// checks all inputs or unchecks all inputs depending if true or false
            });
            $('.case').click(function(){
                if($('.case').length==$('.case:checked').length){
                    $('#selectall').prop('checked','checked');// if all inputs are checked then switch on the #selectall input also
                }else{
                   $('#selectall').prop('checked',false);// else switch off the #selectall input
                }
            });
        });    

Thanks PaulOB

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.