Reputation: 3967
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
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
Reputation: 10077
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
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
Reputation: 646
I think triggering a click event would change the checked state of the checkbox
$(':checkbox').hover(function() {
$(this).trigger('click');
});
Upvotes: 1