0

I have an unordered list of text items with checkboxes beside each of them. I want to perform the same function both when a checkbox is checked/unchecked and when the text is clicked.

Here's what I have right now:

The HTML

<li><input type="checkbox" class="cbox" name="adwords_list[]" value="shave club" ><p class="term"> shave club</p></li>

The JS

$(function() {
    $('ol.phrases li .term').click(function() {
        $cboxStatus = $(this).parent().find('.cbox').prop('checked');

        if ($cboxStatus) {
            $(this).parent().find('.cbox').prop('checked', false);
        } else {
            $(this).parent().find('.cbox').prop('checked', true);
        }
    });
});

$(':checkbox, .term').on('change', function() {
    console.log($(this).prop('checked'));
});

The on.change function isn't calling when the term is clicked. What can I do to get an accurate representation of the checked state no matter what element is clicked/changed?

2
  • 2
    If the adjacent text was a label that targeted the input, you wouldn't need to bind a click event. <li><label><input type="checkbox" class="cbox" name="adwords_list[]" value="shave club" > shave club</label></li> Commented May 9, 2013 at 20:39
  • 1
    Use a label instead of that p. If you successfully pair it with the input, it will actually change the checkbox. Commented May 9, 2013 at 20:40

1 Answer 1

1

If you change the p.term elements to label, with appropriate for attributes matching the associated checkboxes, clicking the text is just the same as checking the box. You then only need to watch the checkbox events.

<input type="checkbox" class="cbox" name="adwords_list[]" value="shave club" id="cb1" />  
<label class="term" for="cb1"> shave club</label>

You can add

.term {
  display: block;
}

etc. to your CSS if you need to match the styling of the p tag.

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

1 Comment

Ugh. Thanks to everyone. That was an utter web development 101 fail.

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.