简体   繁体   中英

JQuery trying to check a checkbox

I am trying to check a check box with jquery alone and then doing a return false as there is other jquery methods i dont want to affect the check box. But for some reason the check box is not checking or unchecking. I need the return false in there as there is other functions which affect the outside element of the checkbox.

 $("#p h1 input").click(function (event) {

    if ($(this).is(':checked'))
    {
        $(this).prop('checked', false);
    }
    else
    {
        $(this).prop('checked', true);
    }

    return false;
});

ok additional i have this even on the h1

$("#p h1").click(function (event) {
        $(this).next(".content").slideToggle();

        if ($(this).hasClass("on")) {
            $(this).find("span").addClass("fa-angle-up");
            $(this).find("span").removeClass("fa-angle-down");
        }
        else {
            $(this).find("span").removeClass("fa-angle-up");
            $(this).find("span").addClass("fa-angle-down");
        }

        $(this).toggleClass("on");
    });

The check box is inside the h1.

I don't want the slide function or anything from the second click event to occur when the checkbox is clicked.

This is the html

<h1>Set<span class="fa fa-angle-up"></span>@Html.CheckBoxFor(model => model.Confirm)</h1>

I don't want the slide function or anything from the second click event to occur when the checkbox is clicked.

In this case you can check what the target of the event was, and not perform your logic if it was the checkbox. To do this you can use jQuery's is() function.

Also note that your if logic can be simplified by simply using toggleClass() instead. Try this:

 $("#p h1").click(function(e) { if ($(e.target).is(':checkbox')) return; var $h1 = $(this); $h1.next(".content").slideToggle(); $h1.toggleClass('on').find('span').toggleClass('fa-angle-up fa-angle-down'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" /> <div id="p"> <h1 class="on"> Set <span class="fa fa-angle-up"></span> <input type="checkbox" name="Confirm" /> </h1> </div> 

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