0

Ok so I need to be able to click any element inside .modal-interest, and it for it to check the child-element checkbox when they are clicked.

Currently, it seems to work for the first click - but for every subsequent click, even though the code is supposed to be checking the checkbox, it does nothing.

$('.modal-interest strong').click(function (e) {

 input = $(this).closest('.modal-interest').find('input');

 if (input.prop('checked')) {
     input.attr('checked', false).change();
 } else {
     input.attr('checked', true).change();
 }
});

An accurate representation of my problem can be seen on the following fiddle:

http://jsfiddle.net/c3p5m/

Stuck with this and would appreciate any help!

4 Answers 4

1

Use .prop() to set checked/Unchecked

input.prop('checked', false).change();

Fiddle Demo

Sign up to request clarification or add additional context in comments.

Comments

1

You should use .prop() instead:

DEMO jsFiddle

 $('.modal-interest strong').click(function (e) {

     input = $(this).closest('.modal-interest').find('input');

     if (input.prop('checked')) {
         input.prop('checked', false).change();
         $('h1').html('untick it');
     } else {
         input.prop('checked', true).change();
         $('h1').html('tick it');
     }
 });

Now indeed, your code should look like this instead:

$('.modal-interest strong').click(function (e) {
    var input = $(this).closest('.modal-interest').find('input')[0];
    input.checked = !input.checked;
    $(input).change();
});
$('.modal-interest input[type=checkbox]').on('change', function () {
    $('h1').html(this.checked ? 'tick it' : 'untick it');
});

DEMO

Comments

0

The prop method should be used.

input.prop('checked', false).change();

Comments

0

Try this code:

 $('.modal-interest').click(function () {

     var input = $(this).find('input');

     if (input.prop('checked')) {
         input.prop('checked', false).change();
         $('h1').html('untick it');
     } else {
         input.prop('checked', true).change();
         $('h1').html('tick it');
     }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.