单击 div 时更改复选框状态(真/假)

Tox*_*xic 5 html checkbox jquery

我有一个带有图像、标签和输入复选框的 div。当我点击 div 时,我喜欢什么,它会将复选框状态从 true 更改为 false ,并且反之亦然

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"));
});
Run Code Online (Sandbox Code Playgroud)

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 />
Run Code Online (Sandbox Code Playgroud)

Ilu*_*Ilu 6

您可以使用选择器选择children('input[type="checkbox"]')复选框并使用以下代码更改其状态

$('.markerDiv').on('click', function(){
   var checkbox = $(this).children('input[type="checkbox"]');
   checkbox.prop('checked', !checkbox.prop('checked'));
});
Run Code Online (Sandbox Code Playgroud)


Jer*_*yal 6

您无需编写任何 javaScript/jQuery 方法即可完成此操作。

只需将 div 包裹在标签内即可:-

div {
  background: red;
  padding: 10px 40px;
}
Run Code Online (Sandbox Code Playgroud)
<label for="myCheck">
  <div>
    <input id="myCheck" type="checkbox" />Remember Me!
  </div>
</label>
Run Code Online (Sandbox Code Playgroud)

  • 元素 div 不允许作为元素 label 的子元素。http://stackoverflow.com/questions/18609554/is-div-inside-label-block- Correct (2认同)

Tox*_*xic 1

按照您在本博客中的指导使用 prop。由于您的复选框位于 div 中,并且 div 注册了单击事件,因此它可能会阻止您使用复选框。使用 e.stopPropagation 使复选框本身也可单击。

$('.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();
 });
Run Code Online (Sandbox Code Playgroud)