Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

forms - Jquery toggle event is messing with checkbox value

I'm using Jquery's toggle event to do some stuff when a user clicks a checkbox, like this:

$('input#myId').toggle(
function(){
//do stuff  
},
function(){
//do other stuff    
}
);

The problem is that the checkbox isn't being ticked when I click on the checkbox. (All the stuff I've put into the toggle event is working properly.)

I've tried the following:

$('input#myId').attr('checked', 'checked');

and

$(this).attr('checked', 'checked');

and even simply

return true;

But nothing is working. Can anyone tell me where I'm going wrong?

Edit - thanks to all who replied. Dreas' answer very nearly worked for me, except for the part that checked the attribute. This works perfectly (although it's a bit hacky)

$('input#myInput').change(function ()
{
    if(!$(this).hasClass("checked"))
    {
        //do stuff if the checkbox isn't checked
        $(this).addClass("checked");
        return;
    }

    //do stuff if the checkbox isn't checked
    $(this).removeClass('checked');
});

Thanks again to all who replied.

question from:https://stackoverflow.com/questions/355638/jquery-toggle-event-is-messing-with-checkbox-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use the change event instead of the toggle event, like such:

$('input#myId').change(function () {
    if ($(this).attr("checked")) {
        //do the stuff that you would do when 'checked'

        return;
    }
    //Here do the stuff you want to do when 'unchecked'
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...