Pranav C Balan Pranav C Balan - 7 months ago 13
Javascript Question

Why first one treat it as boolean value and second not?

I want to toggle the state of two div's based on the radio button. Based on the value I want to toggle div's visibility. First div showing and hiding based on

this.value
but second case I'm using
!this.value
it's not working , also I've tried
!Boolean(this.value)
.



$('[name="radio"]').change(function() {
console.log(this.value,!this.value);
$('#first').toggle(this.value); // this works
$('#second').toggle(!this.value); // this one not
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />

<div id="first">1</div>
<div id="second">2</div>






Why first one treat it as Boolean value and second not?

Answer

Because this.value is a string either 'true' or 'false' both are truthy values so negating it will always give false. That is your second condition will never be true

$('[name="radio"]').change(function() {
  console.log(this.value, !this.value);
  var value = this.value === 'true';
  $('#first').toggle(value);
  $('#second').toggle(!value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="radio" value="false" />
<input type="radio" name="radio" value="true" />

<div id="first">1</div>
<div id="second">2</div>

Also have a look at the toggle() method

toggle: function( state ) {
    if ( typeof state === "boolean" ) {
        return state ? this.show() : this.hide();
    }

    return this.each(function() {
        if ( isHidden( this ) ) {
            jQuery( this ).show();
        } else {
            jQuery( this ).hide();
        }
    });
}

As you can see, of the value is not of type boolean then it is not considered, since for the first one you are passing a string it is always toggled