Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JQuery (!) not assignment returning only false

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.

like image 923
wupendra Avatar asked Feb 13 '26 06:02

wupendra


1 Answers

The issue is because any non-empty string coerces to true, even if it contains the word "false", or the number "0". As such, !"false" is always false.

To fix this you need to use !!. The right ! converts the string to a boolean and the left ! operator inverts that result.

$('div').on('click', '.required_field', function() {
  let v = !!$(this).siblings('input').val();    
  $(this).siblings('input').val(v);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
like image 171
Rory McCrossan Avatar answered Feb 15 '26 12:02

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!