简体   繁体   English

使用JQuery选中/取消选中一个框

[英]Checking/unchecking a box with JQuery

I'm having some trouble using JQuery to check and uncheck an input. 我在使用JQuery来检查和取消检查输入时遇到了一些麻烦。 I know that .prop is the proper way to do it, but it doesn't seem to be working for me. 我知道.prop是执行此操作的正确方法,但它似乎不适用于我。 Here's my code: 这是我的代码:

HTML: HTML:

<div class="checkwrap"><input name="mentoringType" type="checkbox" checked="false" value="test">test</div>

JS: JS:

$('.checkwrap').click(function() {
    if ($(this).find('input').is(':checked')){
        $(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',false);
    } else {
        $(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',true);
    }
});

The input is wrapped for styling purposes. 输入是出于样式目的而包装的。 If I use .attr('checked',true/false) instead, then it works to change the checked property to checked , but it does not uncheck. 如果我改用.attr('checked',true / false),则它可以将checked属性更改为checked ,但不会取消选中。 What's going on? 这是怎么回事?

Eggplant is right: you should use a lebel element to make "test" clickable. 茄子是对的:您应该使用lebel元素使“测试”可点击。

To answer your question: Your skript does work, when only the text ist clicked. 回答您的问题:仅当单击文本ist时,您的skript才能工作。

It also works, but not as expected, when the checkbox is clicked. 单击复选框后,它也可以工作,但不符合预期。 In this case your code leads to a duplication of the ation executed, because the click event bubbles up the DOM tree. 在这种情况下,您的代码将导致重复执行操作,因为click事件使DOM树冒泡。

If the checkbox is not selected, a click on it makes it being selected and your code comes in, detects it as being selected and unselects it again. 如果未选中该复选框,则单击它会使其处于选中状态,并且您的代码会进入,将其检测为选中状态并再次取消选中它。

For an unselected box it works vice versa. 对于未选中的框,反之亦然。

But as stated before: you should have chosen a label in the first place. 但是如前所述:您应该首先选择一个标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM