简体   繁体   中英

jquery uncheck and check and vise versa checkbox of child element

Here is my html

#This will be generated throught loop

<li class="selector">
    <a>
    <input type="checkbox" value="test" /> test
    </a>
</li>

Here is my jquery click event

$('.selector').on('click', function() {
    if($(this).find('input').is(':checked')){
    #uncheck the checkbox       
    }else{
    #check the checkbox
    }
});

How do I uncheck if checked and check if unchecked

Try

$(document).on('click', '.selector', function (e) {
    if (!$(e.target).is('input')) {
        $(this).find('input').prop('checked', function () {
            return !this.checked;
        });
    }
});

Demo: Fiddle

Another way

$(document).on('click', '.selector', function (e) {
    $(this).find('input').prop('checked', function () {
        return !this.checked;
    });
});
$(document).on('click', '.selector input', function (e) {
    e.stopPropagation();
});

Demo: Fiddle

Try this

$('.selector').on('click', function() {
        var checkbox = $(this).find(':checkbox');
        if($(checkbox).is(':checked')){
             $(checkbox).prop('checked', false);     
        }else{
        #check the checkbox
             $(checkbox).prop('checked', true);
        }
    });

I don't understand why you are trying to do this with JavaScript. If the user clicks directly on the checkbox it will automatically check/uncheck itself, but if you add code to check/uncheck it in JS that would cancel out the default behaviour so in your click handler you'd need to test that the click was elsewhere within the .selector .

Anwyay, the .prop() method has you covered:

$('.selector').on('click', function(e) {
    if (e.target.type === "checkbox") return; // do nothing if checkbox clicked directly
    $(this).find("input[type=checkbox]").prop("checked", function(i,v) {
        return !v; // set to opposite of current value
    });
});

Demo: http://jsfiddle.net/N4crP/1/

However, if your goal is just to allow clicking on the text "test" to click the box you don't need JavaScript because that's what a <label> element does:

<li class="selector">
    <label>
    <input type="checkbox" value="test" /> test
    </label>
</li>

As you can see in this demo: http://jsfiddle.net/N4crP/2/ - clicking on the text "test" or the checkbox will toggle the current value without any JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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