0

I have this list of li's that have a check-box that goes with it. I'm trying to have the check-box checked toggled when the li is clicked. Im trying to get it to use the "this" key word so that only the checkbox in the li that is clicked gets checked but cant figure it out. Here is my code.

<form method="get">
    <ul>
         <li class="check"> <input type="checkbox" name="cause1" value="cause1" class="cause1">check 1</li> 
         <li class="check"> <input type="checkbox" name="cause3" value="cause3" class="cause2"> check 2</li> 
         <li class="check"> <input type="checkbox" name="cause4" value="cause4" class="cause3">check 3</li> 
         <li class="check"> <input type="checkbox" name="cause5" value="cause5" class="cause4"> check 4</li>               
         <li class="check"> <input type="checkbox" name="cause6" value="cause6" class="cause5"> check 5</li> 
    </ul>
</form>

        <script>
            $(document).ready(function () {
                $('.check').click(function () {
                    $(this).each(function () { 
                        if (this.checked = false;) {
                            $(this).checked = true;
                        } else {
                            $(this).checked = false;
                        }
                    });
                });
            });

        </script>
nick
  • 1,226
  • 3
  • 21
  • 38
  • Your if statement doesnot contain comparison operator(===), it's assignment(=), and it does contain a semicolon(;), just minor syntactical problems, not the solution. – Prateek Mar 04 '14 at 01:22
  • I didn't get what do you really want to do? when you click on the li item you want the other check items to be toggeled? or what ? – user2517028 Mar 04 '14 at 01:24
  • [link](http://stackoverflow.com/questions/3408150/add-attribute-checked-on-click-jquery), may be what you were looking for, but try without each, – Prateek Mar 04 '14 at 01:25

3 Answers3

1

Your if statements are set up wrong, you've got assignment operators in there and also a semicolon. Also try using the this selector and attr() instead as well.

if( !( $(this).attr('checked') ) ){
    $(this).attr('checked', 'checked');
}

I always use attr() for checking and assigning checkbox values as well.

domdomcodecode
  • 2,355
  • 4
  • 19
  • 27
1

Try this

$('.check').click(function () {
   if($(this).find('input').is(':checked'))
       $(this).find('input').prop('checked',false);
   else
       $(this).find('input').prop('checked',true);
});
robert
  • 609
  • 6
  • 14
1

Try

jQuery(function ($) {
    $('.check').click(function (e) {
        //ignore the click on the input element else the default behavior and manual toggle will negate each other
        if (e.target.tagName != 'INPUT') {
            $(this).find('input').prop('checked', function (i, checked) {
                return !checked
            });
        }
    });
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531