I am working on a project and have a lot of boolean fields. I want these fields to return boolean value(1 or 0). I don't know if its an embarrassing question but I cant change the value of the input by not (!)
assignment in jQuery. It works for 2 clicks and after that it always returns false
. In first click since the value of the hidden input is empty it returns true
, on second click it returns false
as !true=false
. After that on all the clicks it only returns false
.
My Html
<div class="col-md-4">
<label>Required?</label>
<input type="checkbox" name="" class="form-control required_field">
<input type="hidden" name="field_required[]" value="">
</div>
My Jquery
$('div').on('click', '.required_field', function() {
let v = !($(this).siblings('input').val());
$(this).siblings('input').val(v);
console.log($(this).siblings('input').val());
});
It works with ternary operators and if else
, if I compare with values as:
$('.div').on('click','.required_field',function(){
$(this).siblings('input').val(($(this).siblings('input').val()==1)?0:1);
console.log($(this).siblings('input').val());
});
Or
$('.up-field-sec').on('click','.required_field',function(){
let v = $(this).siblings('input').val();
$(this).siblings('input').val((!$(this).siblings('input').val() || v==0)?1:0);
console.log($(this).siblings('input').val());
});
I find it very strange how can it be !false = false
?? What am I missing here? This is bugging me. I would be very glad if anyone can explain this to me. Thank you in advance.
Here is the Jsfiddle of the code.