Question

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>
Était-ce utile?

La solution

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

Autres conseils

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.

Try this

$('.check').click(function () {
   if($(this).find('input').is(':checked'))
       $(this).find('input').prop('checked',false);
   else
       $(this).find('input').prop('checked',true);
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top