Strange data-attribute boolean issue - javascript

I have a live -on click- event for a Header which has an arrow flipping up/down upon opening & closing it's contents.
The strangest thing is happening with ! followed by a variable -- which is supposed to flip it from true -> false, and vice versa. Basically it's not working at all, and it flips to false and stays there... Check out the fiddle to see what I mean.
I've deleted lots of code for the sake of brevity.
Demo Code
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).attr('data-state');
if (_state === 'true') {
// do stuff
}
else {
// do stuff
}
// This is where the issue is happening, it isn't flipping the Boolean value
// !"true" = false, !true = false, it works with strings or booleans
$(this).attr('data-state', !_state);
});​
I can get it working perfectly fine if I do the following:
if (_state === 'true') {
// Manually flip the data-state boolean
$(this).attr('data-state', false);
}
Is there something I'm missing why this isn't working the way it should ?? Just wondering why it's doing this!

I think you are trying to do this:
http://jsfiddle.net/JKUJb/2/
if so, the problem was that you are using .attr() which returns a string, so if you convert:
!"true" //false
!"false" //false
.data() on the other hand returns the value already "casted
EDIT:
Just to be more clear, in javascript the only falsy values are:
false;
null;
undefined;
'';
0;
NaN;
So if you really wanted to use .attr(), you could, but I recommend that first you do:
var _state = $(this).attr('data-state') === 'true'; //if 'true' then true, false otherwise
Good luck!

Change your second line to:
var _state = $(this).attr('data-state') == 'true';
And in the if statement check for boolean:
if ( _state ) {
// do stuff
...

_state is a String (typeof _state === String //true) you need to convert it to a boolean first
(a String will alwase be true)

If you really want to use data- attributes for this, use jQuery's .data method to retrieve and set the value. It will automatically convert the string "true" into a Boolean, or the string "1" into a number:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).data('state');
if (_state) {
// do something
}
$(this).data('state', !_state);
});​
http://jsfiddle.net/mblase75/JKUJb/6/
Or you could toggle a class -- you can use the .hasClass method to return a Boolean:
$(document).on('click', '.regimenHeader', function () {
var _state = $(this).hasClass('data-state');
if (_state) {
// do something
}
$(this).toggleClass('data-state');
});​
http://jsfiddle.net/mblase75/JKUJb/3/

Related

How to change a boolean value in JS?

I'm trying to make a button with two functions:
function bigfont()
{var font_is_small = true
if (font_is_small = true)
{document.getElementById('one').className=
document.getElementById('one').className.replace("font1","font2");
document.getElementById('two').className=
document.getElementById('two').className.replace("font1","font2");
document.getElementById('three').className=
document.getElementById('three').className.replace("font1","font2");
document.getElementById('four').className=
document.getElementById('four').className.replace("font3","font4");
font_is_small = true;}
if(font_is_small = false)
{document.getElementById('one').className=
document.getElementById('one').className.replace("font2","font1");
document.getElementById('two').className=
document.getElementById('two').className.replace("font2","font1");
document.getElementById('three').className=
document.getElementById('three').className.replace("font2","font1");
document.getElementById('four').className=
document.getElementById('four').className.replace("font4","font3");
font_is_small = true;}}
But the variable doesn't change. Could anybody help me?
To change a boolean to its opposite value you can use negation (!), for example x = !x means "set x to false if it's truthy or to true if it's falsy".
If you want the function to toggle between small and big font the simplest way is to place te variable outside of the function:
http://jsfiddle.net/zvoeLu9p/
var font_is_small = true;
function bigfont()
{
font_is_small = !font_is_small; // switch the boolean
if (font_is_small){ // no need for == true
document.body.className=
document.body.className.replace("font1","font2");
}
else { // no need for if condition
document.body.className=
document.body.className.replace("font2","font1");
}
}
But you have the variable font_is_small in true all the time you have to change it to false in your code you don't do this.
It's where your variable is created and assigned, your equivalence in the if (= means assign) and you are setting it to true in BOTH if statements. ... try ...
var font_is_small = true;
Based on your usage, font_is_small should be a global, not passed in or created inside the function.
function bigfont() {
if (font_is_small === true) {
document.getElementById('one').className="font2":
document.getElementById('two').className="font2":
document.getElementById('three').className="font2":
document.getElementById('four').className="font2":
font_is_small = false;
}
if(font_is_small === false) {
document.getElementById('one').className="font1":
document.getElementById('two').className="font1":
document.getElementById('three').className="font1":
document.getElementById('four').className="font1":
font_is_small = true;
}
}
Also, the replace wasn't doing anything significant ... I figured out the two line formatting after fixing this ... this assignment is simpler and clearer.

javascript if statement checking for true/false

I wrote, what I thought, was a straight forward if statement in JS but it is running incorrectly.
function printLetter(LetterId) {
var studentflag = $("#IsStudent").val();
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
Everytime it runs, the studentflag var value is correct, but regardless of whether it is true or false, it goes into option 1. I am pretty sure I have done true/false checks like this before in JS, but do I need to spell it out (studentflag == true) instead?
This is known as truthy and falsy Values
The following values are always falsy:
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
All other values are truthy:
including "0" (zero in quotes),
"false" (false in quotes) like if (studentflag) //being studentflag "false",
empty functions,
empty arrays, and
empty objects.
If #StudentFlag is either "true" or "false", then if(studentFlag) will always follow the true route because both are non-empty strings (truthy). You need to do something along these lines:
var studentflag = $("#IsStudent").val();
if (studentflag === "true") {
//do option 1
} else {
//do option 2
}
.val () doesn't return a boolean.
Try this instead;
function printLetter(LetterId) {
var studentflag = $("#IsStudent").is (':checked');
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
This is assuming #IsStudent is a checkbox. If it's not, try this (assuming the value is true (as a string, not a boolean));
function printLetter(LetterId) {
var studentflag = ($("#IsStudent").val () == 'true')
if (studentflag)
{
//do option 1
} else {
//do option 2
}
}
IMO there should be more context in the question. If submitted solution works for OP that is great, but for others using this as a resource, the accepted solution might not work in all cases.
The value retrieved from an element via JS actually depends on the input itself and its HTML structure. Here's a demo explaining the difference between using .val(), .attr('val'), and .is(':checked') with checkboxes and radios. All of those variants can pull different values from an element depending on its HTML structure and current UI state.
Fiddle : http://jsfiddle.net/h6csLaun/2/
var studentflag = $("#IsStudent").val();//This is a string .. not a boolean
if (studentflag === "true") //therefore this has to be string comparison
Or you can make studentflag boolean as follows:
var studentflag = $("#IsStudent").val() === "true";
if (studentflag) { ....

If condition on windows load not working in javascript

The following code is not working and cant understand why. What am I doing wrong?
$(function() {
var advanced = localStorage['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")|(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
Check the OR operator. It should be like -
if((advanced == "true")||(advanced==true)){
This expression is not working:
if((advanced == "true")|(advanced==true)){
It’s enough to do:
if(advanced) {
because "true" as a string is also "truthy".
You are missing an extra |:
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true") || (advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
OR operator needs to be two |..Like this:
if((advanced == "true") || (advanced==true)){
If the variable advanced is a BOOLEAN, then you can simply use this:
if(advanced) {
// code here..
}
I think there is mistake in your javascript code.so you can not use "|" instead of "||"
so try by the following code gets solved your error.
$(function() {
var advanced = localStorage.getItem['advanced-search'];
alert(advanced);//this shows true
if((advanced == "true")||(advanced==true)){
//Code never reaches here
alert('click');
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = false;
}
});
As you say that a proper OR operator is still not working, then I suspect it must be a problem with the case.
Check this fiddle: http://jsfiddle.net/VTfQU/
Use this code to simplify your if condition:
var advanced = localStorage.getItem['advanced-search'];
advanced = advanced.toString().toLowerCase();
if (advanced == "true") {
$('#advanced-search').trigger('click');
localStorage['advanced-search'] = "false";
}
The idea is to convert your data into lowercase and then just check the condition on that value. I have added toString() just to be safe, anyway getting a value out of local storage will always be a string.

Check if an object exists by its selector, return a boolean value with jQuery or Javascript

I need to see if an object is present on the page by its selector.
This WOULD normally do it:
startpageentry = $('#' + startpageid)
But that doesn't return anything. I need a boolean I can put into an if statement like this:
if (startpageentry != 'false') {}
How can I do this?
Use length:
var startpageentry = $('#' + startpageid).length;
To store boolean result, use:
var isPresent = $('#' + startpageid).length > 0;
Now isPresent will be true if it exists false otherwise.
Or simply:
if ($('#' + startpageid).length){
// exists
}
else {
// does not exist
}
There is no boolean for that because it would prevent from chaining.
You could use $(something).length>0.
But if you need to run in over and over again, I made a little jQuery plugin which is called doesExist()
/* doesExist PLUGIN (c) MS */
/* (c) Michael Stadler(MS), */
(function($){
$.fn.doesExist = function()
{
return jQuery(this).length > 0;
};
})(jQuery);
The usage of it would be
if($('#something').doesExist()){
//doesExist returns a boolean
}
To get a Boolean with jQuery...
var startpageentry = !! $('#' + startpageid).length;
Without jQuery...
var startpageentry = !! document.getElementById(startpageid);
Of course, you don't really need a Boolean to test it. You could just rely on 0 being falsey (for the jQuery version) or null being falsey (for the non jQuery version).
Also, your but that doesn't return anything isn't correct. It would return a reference to the jQuery object returned. Objects in JavaScript are always truthy, so testing it in a condition won't tell you if the selector matched any elements or not.

Javascript equality weirdness

I'm trying to fetch some data through ajax. One of the data determines whether or not a checkbox should be checked by default. If the returned variable isVisible is 1, then it should be checked, if its 0 then it should be unchecked. Here's the code:
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
} );
Later on in the code:
var isChecked = (isVisible) ? true : false;
$("#visible").attr('checked', isChecked);
The problem is that, whether or not isVisible is set to 1 or 0, the checked variable is always being evaluated to true. I'm really not sure what the problem is. Perhaps isVisible is being treated as a string ?? How do I resolve this?
Probably isVisible is a string. "0" is a truthy value in Javascript. Use this instead:
var checked = (isVisible==="1") ? true : false;
How about
isVisible = (result.isVisible == "1")
?
I guess "isVisible" is a string not a number, so it pass the test.
Try parseint(isVisible, 10), an let me know
Ajax is asynchronous. you need to use callbacks.
$.getJSON(myUrl, function(result)
{
isVisible = result.isVisible;
// snip...
callback_setvis();
} );
function callback_setvis(){
var ischecked = (isVisible) ? true : false;
$("#visible").attr('checked', ischecked);
}
After reviewing your question again it seems the above might not work.
This might be an issue of attr vs prop
if you are in jQuery 1.6 or greater you should do:
$("#visible").prop('checked', ischecked);

Categories