toxic toxic - 7 months ago 21
Javascript Question

change checkbox status (true/ false) on div click

i have div that have image, label and input check-box. what i like when i click on div, it change check-box status from true to false and vise verse

jQuery

$(".markerDiv").click(function () {

if ($(this).find('input:checkbox[name=markerType]').is(":checked")) {

$(this).find('input:checkbox[name=markerType]').attr("checked", false);
}
else {
$(this).find('input:checkbox[name=markerType]').attr("checked", true);
}


alert($(this).find('input:checkbox[name=markerType]').is(":checked"));
});


html

<div class="markerDiv" id="maker_school"><label class="marker_label">School</label> <input class="marker_ckeckbox" name="markerType" value="school" type="checkbox" /> </div> <br />

Answer

use prop as you been guide through out this blog. As your check-box is in div and because div is registered with click event, it may stop you using check-box. Use e.stopPropagation to make check-box itself click-able too.

$('.markerDiv').click(function () {

  if ($(this).find('input:checkbox[name=markerType]').is(":checked")) {

    $(this).find('input:checkbox[name=markerType]').attr("checked", false);
  }
  else {
      $(this).find('input:checkbox[name=markerType]').prop("checked", true);
  }

   alert($(this).find('input:checkbox[name=markerType]').is(":checked"));
});


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