I have a simple bit of code to show a div of information if a checkbox has been checked, and to hide that div if it is not checked. While building, I ran into an issue that I cannot find any information to resolve. To simplify the problem, I have an if statement, and if the input is checked, it will log "checked". if it isn't checked, it will log "not checked".
$("#my-id") is a div containing a label with a checkbox input inside it
<div id='my-id'>
<span>
<label>
<input type="checkbox">
test
</label>
</span>
</div>
so clicking on it selects and deselects the checkbox input.
$("#my-id").unbind('click').click(function(){
if($(this).find('input').is(':checked')){
console.log('checked');
}
else {
console.log('not checked');
}
});
What I'm seeing in the log with one click is:
not checked
checked
Then when I click the same one again, is shows
checked
not checked
This is messing with the slideUp() and slideDown() functions because they end up getting called twice, and I have parts of my page sliding up and down and up and down. Any insight would be greatly appreciated. I'm sure there is something about JQuery, or it's functions that I do not understand yet.
CodePudding user response:
This seems to happen only when you click on the <label>
tag. When you click the <div>
, <span>
, or <input>
it works correctly.
This behavior might be explained here: Why the onclick element will trigger twice for label element.
One fix is to add return false;
to your click handler:
$("#my-id").unbind('click').click(function(){
if($(this).find('input').is(':checked')){
console.log('checked');
}
else {
console.log('not checked');
}
return false; // Prevents event handler from being called twice
});
You can also call .preventDefault()
on the event object to prevent it from being called twice:
$("#my-id").unbind('click').click(function(e){
if($(this).find('input').is(':checked')){
console.log('checked');
}
else {
console.log('not checked');
}
e.preventDefault();
});