itamar
itamar

Reputation: 3967

Checking and Unchecking Checkbox with Jquery

I am trying to get a checkbox to check and uncheck if it isn't/is checked. It is checking if unchecked - but not unchecking if yes checked. Very strange. Thanks in advance!

Here's my code:

EDIT: Here's the jsfiddle: http://jsfiddle.net/itamark/UnR4X/

JS:

$(':checkbox').mouseenter(function(){
    if($(this).not(':checked')) {
        alert('notchecked');
        $(this).attr('checked', true);
    }
    else if($(this).is(':checked')){
        alert('ischecked');
        $(this).attr('checked', false);
    }


})

HTML:

<input type="checkbox" name"myCheck" id="chk1"/>Checkbox</label>

Upvotes: 1

Views: 1341

Answers (5)

Aditya
Aditya

Reputation: 4463

Here is the working fiddle, http://jsfiddle.net/UnR4X/11/

$(':checkbox').mouseenter(function(){
        if($(this).prop('checked')) {
            $(this).prop('checked', false);
             $(this).removeAttr('checked');
        }
        else{
            $(this).prop('checked', true);
            $(this).attr('checked',true);
        }

Upvotes: 1

Rooster
Rooster

Reputation: 10077

Working Fiddle

Note the name param of you input needs an equal. Also, hover the wrong event unless you specify a hover in and hover out handler, other wise the function will just keep functioning. Easier to just use mouseenter handler. Only fires on start of hover that way. If you want something else to happen on mouse leave you can specify a mouseleave. Or you can specify 2 functions to do this in the hover function.

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

})

Upvotes: 1

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33880

.is() and .not() are not the same

.is() return true or false while .not() remove jQuery element if it match.

Therefor, $(selector).not() will always be true since jquery is defined.

To check if the element exist, use .length.

$(':checkbox').hover(function(){
    if($(this).not(':checked').length) {
        $(this).prop('checked', true);
    }
    else if($(this).is(':checked')){
        $(this).prop('checked', false);
    }
})

Fiddle :http://jsfiddle.net/UnR4X/3/

You might aswell use a 1 liner :

$(this).prop('checked', !$(this).prop('checked'));

Upvotes: 4

callmehiphop
callmehiphop

Reputation: 646

I think triggering a click event would change the checked state of the checkbox

$(':checkbox').hover(function() {
  $(this).trigger('click'); 
});

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74410

Use .prop():

$(this).prop('checked', true);
$(this).prop('checked', false);

Upvotes: 1

Related Questions