2

I have a checkbox inside a div which has a click event attached to it. But the checking and unchecking the checkbox directly doesn't work.

<div class="container" onclick="select(this)">
     <input type="checkbox" value="" /><label>Item</label>
</div>

function select(e) {
    var elm = $(e);
    var chkBox = elm.find('input');
    console.log(chkBox.is(':checked'));
    if(chkBox.is(':checked')) {
       chkBox.prop("checked", false);
   }else{
       chkBox.prop("checked", true);
   }
}

Demo : http://jsfiddle.net/h45A5/

3 Answers 3

2

Try to bind event properly rather than using an inline handler,

HTML:

<div class="container">
    <input type="checkbox" value="" /><label>Item</label>
</div>

JS:

$('div.container').click(function(e){
   if($(e.target).is(':checkbox')){ return; }
   var chkBox = $(this).find(':checkbox');
   chkBox.prop("checked", !chkBox.is(':checked'));
});

DEMO

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

Comments

2

You should write var elm = getElementById('e'); instead of var elm = $(e);

Try it yourself: http://jsfiddle.net/h45A5/3/

1 Comment

i want the checkbox to be checked even when the container is selected and also when the checkbox is checked.
1

If I understand correctly, you want the checkbox to toggle if either the div and the checkbox are clicked, in which case, add

$('input[type="checkbox"]').click(function(e){
  e.stopPropagation();
});

Refer updated fiddle

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.