Rebelion
Rebelion

Reputation: 25

switching bool values in Javascript

This is a weird issue: I have a HTML attribute that will only be true or false, i fetch it with Jquery and turn it into a boolean, then i switch it for the opposite (true to false, false to true), then i change the same HTML attribute with the new boolean value.

It works at first, when the original attr value is false and it get set to true, but not the other way around:

<button aria-checked="false" class="toggle-search" type="button">
    Toggle button is <span>false</span>
</button>

And now the Js/Jquery

$(".toggle-search").click(function(){      

    var status = !$(this).attr("aria-checked"); 
    // returns string, turn to bool

    $(this).attr("aria-checked",!status);
    $(this).children("span").html(!status);

});

https://jsfiddle.net/kaqyhc48/4/

I dont understand what's going on with the logic, is the new value not being parsed to false or maybe being parsed to false first and then to true?

Thanks for the help

Upvotes: 1

Views: 1139

Answers (2)

yajiv
yajiv

Reputation: 2941

var status = !$(this).attr("aria-checked"); this will not convert string to bool. So replace it with var status = 'true'== $(this).attr("aria-checked"); which will convert string to bool.

And in .html(false) will not be printed so use .html((false).toString())

$(".toggle-search").click(function(){      

        var status = 'true'== $(this).attr("aria-checked");
        $(this).attr("aria-checked",!status);
        $(this).children("span").html((!status).toString());
        
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button aria-checked="false" class="toggle-search" type="button">
  Toggle button is <span>false</span>
</button>

Upvotes: 0

Sebastian Speitel
Sebastian Speitel

Reputation: 7336

You have to parse the string to a boolean value. The simplest way to do it is value == "true", which returns true, when the string is "true" and false otherwise.

To parse it back to a string you can use value ? "true" : "false".

$(".toggle-search").click(function() {

  var status = $(this).attr("aria-checked") == "true";
  status = !status;
  // returns string, turn to bool

  $(this).attr("aria-checked", status);
  $(this).children("span").html(status ? "true" : "false");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button aria-checked="false" class="toggle-search" type="button">
    Toggle button is <span>false</span>
</button>

Upvotes: 2

Related Questions