Javascript Conditional Not Reaching Else
I'm working on creating a toggle function to 'favorite' an item from a list of many. I've got working script to toggle the item in and out of a user-specific favorites list, commun
Solution 1:
indexOf
returns the 0-based index of where the substring is found, or -1
if not. -1
happens to be "truthy".
That means you have two possibilities, it's either in the string and has a positive (truthy) position, or it's not and you get a truthy -1
. Either way, it will always go into the first block. You want:
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png") > 0){
Solution 2:
You only need to fetch the element once:
var toggle = document.getElementById("faveToggle");
if (toggle.src.indexOf("fave-false.png") >= 0) {
toggle.src = "includes/icons/fave-true.png";
}
else {
toggle.src = "includes/icons/fave-false.png";
}
The .indexOf()
function returns the position of the searched-for substring, or -1
if it isn't found.
Solution 3:
You can checkif it is greater than -1
if(document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")>-1){
alert('1')
document.getElementById('faveToggle').src = "includes/icons/fave-true.png";
} else {
alert("2")
document.getElementById('faveToggle').src = "includes/icons/fave-false.png";
}
Solution 4:
Here's my simplified version using a ternary operator:
var toggle = document.getElementById('faveToggle'),
newState = toggle.src.toString().indexOf("fave-false.png") == -1 ? true : false;
toggle.src = "includes/icons/fave-"+newState+".png";
Solution 5:
You can use the bitwise not ~
operator for checking.
~
is a bitwise not operator. It is perfect for use withindexOf()
, becauseindexOf
returns if found the index0 ... n
and if not-1
:
value ~value boolean -1 => 0 => false 0 => -1 => true 1 => -2 => true 2 => -3 => true and so on
if(~document.getElementById('faveToggle').src.toString().indexOf("fave-false.png")){
Post a Comment for "Javascript Conditional Not Reaching Else"