I'm trying to get a 3-way checkbox to work. For this, I want to handle the click or change action myself... ie decide what the next state will be.
But I struggle at the very begin:
I initialize a checkbox
Set the indeterminate true
Check this runtime => indeterminate=true, checked=false
Got an event handler for a click with a
prevenDefault()
The markup stays unchanged as expected => looks like an indeterminate checkbox
But when I check the values for indeterminate and checked they have toggled none the less
Googling for a solution I found that there are 2 ways to create an event handler
$('.chk').click(function(event){});
And
$('.chk').on('click',function(event){});
I tried both.
Also tried to change instead of click.
Even tried having both click and change, with one of them just having the prevenDefault()
.
I've got a jsfiddle set up:
https://jsfiddle.net/PeterKaagman/rpmL0gv4
$(".chk").prop("indeterminate", true);
$("#out").append("Checked " + $('#chk_1').prop('checked') + "<br>");
$("#out").append("Indeterminate " + $('#chk_1').prop('indeterminate') );
$(".chk").click(function(event){
event.preventDefault();
$("#out").empty();
console.log(this);
$("#out").append("Checked " + this.checked + "<br>");
$("#out").append("Indeterminate " + this.indeterminate );
});
//$(".chk").on(change,function(event){
// event.preventDefault();
//})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>3-way checkbox</p>
<input type="checkbox" class="chk" id="chk_1" >
<div id="out"></div>
Most of it is for debugging as you can see.
What I expected was that the properties checked and indeterminate would not change due to the preventDefault(). Letting me decide the next state of the checkbox.
I'm sure I doing something stupid... could someone plz point it out for me?
Peter