So, I'm new to Javascript. In my code I have an image object that is declared like so:
<img src="me.png" id="changepic" alt="That's me!">
In my scripting code, I want to write a boolean statement that returns true when the src is "me.png" as it is in the picture and returns false if it is NOT "me.png". This boolean statement is located within the conditions of the if statement below:
function changeImage() {
if (document.getElementById("changepic").src === "me.png"){
document.getElementById("changepic").setAttribute("src", "me2.png");
}
}
I assigned the function changeImage to a button. The code for the button is written below:
<button type="button" onclick="changeImage()">Change Image</button>
For some reason, the boolean statement inside of the if statement always returns false, although the src value of the Element really is "me.png." I figured that this is a problem with how I'm writing the equality statement, but I don't know how to write an equality statement in javascript that would return true if the src value is "me.png" and return false if the src value is "me2.png". Any takers?
Change:
if (document.getElementById("changepic").src === "me.png"){
To:
if (document.getElementById("changepic").src.match(/me\.png$/)){
as .src will typically contain a full path to the image even though you don't specify it in the HTML.
The problem is not with your equality, its with
document.getElementById("changepic").src
which, is probably not returning what you think it is returning. Try a
console.log(document.getElementById("changepic").src)
and verify that it really is "me.png". I bet its something else.
Be aware that in js, === tests equality of both type and value, where as == will test equality more loosely; it is more forgiving. for example
2 === "2" // false because not the same type
2 == "2" // true because == tries to make the types lines up, then tests
"Relative URIs are resolved to full URIs using a base URI. [RFC1808], section 3, defines the normative algorithm for this process. For more information about base URIs, please consult the section on base URIs in the chapter on links."
From here: http://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-uri
You should just look at the "right-most" characters when you compare.
For example
var mystr = document.getElementById("changepic").src
mystr.substr(len(mystr)-6,6) === "me.png"
Related
I have an app platform which is developed on "Edge". And my app is built on eclipse. In javascript files of my code many times i have declared my variables with boolean. But to run app on platform i have to convert these boolean values to string like "true". Then only i can set it true. In a big code it is not good to convert boolean to string everywhere. So is it possible that wherever i am having boolean value it can detect and convert to string so that the app platform developed on Edge can understand it ?
Why would you try to print out boolean values in the first place? Check to see if value is boolean where you are alert(value);
For example,
var value = true; // Somewhere in code
if (value == true) { // Just check if value is true/false
alert("true");
} else {
alert("false");
}
Your approach is unnecessary and you are making the problem more complex then needs to be. There is no way to check if a value is boolean while the code is running, so you are going to have to change it everywhere you want alert("true"); Sadly, you can't hack this with a different approach.
I'm rather new to this and don't know exactly how to report a bug, but I first want to confirm it's a bug and then go on from there. But here's what I'm finding:
1) When creating an audio object controls attribute, the controls attribute will respond to a string as if it's a boolean.
For Instance:
<button onclick="example()">Try this</button>
<script>
function example() {
var aud = document.createElement("AUDIO");
aud.setAttribute("src","example.mp3");
aud.setAttribute("controls", "controls");
}
Okay, we've put controls in there because it makes controls equal controls:
Thing is, you can put any old string in there and it works just fine -- apple, banana, pear, anything.
2) Isn't the value suppose to be a boolean? Well when you try a boolean, false for example, you still get true. (False == True) It works just as if you typed in true.
...and if you put anything else other than true or false (just type anything other than an integer, string, or true or false value), you get false (or it just doesn't work).
Everything equals true and a non-string, non-integer equals false (or just doesn't work).
Finally, you can even try setting the controls attribute on an accessed audio element:
var aud = document.getElementById("idhere");
function accessAudioElement() {
aud.controls = false;
}
At least here the true and false actually work as true and false, but once again, any string or integer will also get you true and any non-string/non-integer will break the code.
Can somebody help me out here because I don't think this is suppose to work this way... and if does, what's the point of using a boolean value when most anything else will work?
Of course I'm still learning, so maybe this is not a bug, maybe for some reason this is suppose to work this way, but if that's the case would someone please share the logic behind this with me.
I'm just not understanding.
Thanks Magic
This is an extended answer of what #nnnnnn suggested in the comments.
aud.controls = false; doesn't set the attribute, it sets the property.
You need to use setAttribute() method to add the specified attribute to an element.
aud.setAttribute("controls", "controls");
And use removeAttribute() method removes the specified attribute from an element.
aud.removeAttribute("controls");
For more reading on these methods, have a look at the hyperlinks attached.
Element.setAttribute()
Element.removeAttribute()
When to use setAttribute vs .attribute= in JavaScript?
HTML - attributes vs properties
You might want to read/search more about Javascript Truthy $ Falsey. It is very important.
https://j11y.io/javascript/truthy-falsey/
Made a boolean variable "disableReplaceDate", used in if-statements. Have to save the variable somehow because the page reloads and I need to use it to "check a status" sort of, so it doesn't return to default every time the page reloads.
Then, to save myself a lot of time and trouble, because I can't send them in the URL as parameters(it's occupied already by a complicated java file which manipulates it all and I'm no good at java at all), I decided to use window.localStorage setItem, getItem and removeItem etc., so basically
var disableReplaceDate = false;
window.localStorage.setItem("dRD", false);
disableReplaceDate = window.localStorage.getItem("dRD");
But now the if-statement, which looked as follows:
if(disableReplaceDate == true){/*do some stuff*/}
didn't work anymore! But then when I changed it to
if(disableReplaceDate){/*do some stuff*/}
It starts working suddenly.
And if that wasn't uncanny enough, it won't do this for all if-statements using the variable, I tried changing them to (!disableReplaceDate) and such, but it doesn't make them work.
Why is this? And how do I solve it?
localStorage only stores strings. And "false" evaluates as true in a context where a boolean is needed (for example a if statement).
You should change
disableReplaceDate = window.localStorage.getItem("dRD");
to
disableReplaceDate = window.localStorage.getItem("dRD") === "true";
I think because the type of your variable is "string" see this
typeof(disableReplaceDate)
The output will be string
I think you need to test this way if(disableReplaceDate === "false")
I am working on a c++ web-based IDE for beginners where one of it's core function is to let the user know the evaluation result (true or false) of the conditional statement they have on my contenteditable div.
Say i am already able to fetch the "fragment" (what i call it based on my architecture) that i wanted to evaluate and i already know the values of the variables...
Can you please suggest a way on how would i evaluate the text on the fragment as a conditional statement that will return either true or false...
Example
when var b = 5;
$('.frag').eq(1).text() //"if( (b>1) || (b==10) )"
after evaluation(what im asking for help) should return true
$('.frag').eq(2).text() //"(b>1)"
should return true
**$('.frag').eq(3).text() //"(b==10)"
should return false
UPDATE
The problem i am seeing with eval is that if i have a var1 in the contenteditable div and i have a var1 in my code. I should put a header on the variables from the contenteditable then right? like sc_var1 to prevent messing up with var1 from my source code?
You can use Eval like this:
var expression = $('.frag').eq(1).text();
var result = eval(expression);
However I generally do not recommend using eval because there is always a much better workaround.
if I get the bigger picture of your needs I would be able to provide a better solution.
This question already has answers here:
Are empty HTML data attributes valid?
(4 answers)
Closed 7 years ago.
I am wondering if html data attributes actually need a value to be applied?
I wonder this because often all we want to know is if the attribute is actually set to act as a flag. (sure we could use a class for this; but realistically unless you are going to style these items differently then the flags are more data than a semantic item).
A perfect example of this is if we want a link to scroll to it's target instead of jumping our jQuery code might look like:
$(document).on('click', '[data-scroll-link'], function(){/**do scroll**/});
I know in google chrome it is sufficient for the anchor to appear as
<a href="#bottom" data-scroll-link>Scroll to bottom</a>
But will that work everywhere? and is it even valid HTML5 (I believe it is due to the autofocus, autoplay etc attributes). or do we need:
Scroll to bottom
No. But...
As is common with all attributes, in the application/xhtml+xml serialisation, XML rules apply and the attribute must have an explicit name and (quoted) value.
So this question is really about the text/html serialisation, and therefore the relevant part of the HTML5 spec is Section 8 The HTML syntax
In particular, under attributes, it says:
Attributes can be specified in four different ways:
where the first of these is:
Empty attribute syntax
Just the attribute name. The value is implicitly the empty string.
It's necessary to understand though that the value is of string type, not of boolean type.
For example, with <input id="cb" type="checkbox" checked>, the "checked" attribute is reflected by a property that is either true or false. So
if (document.getElementById("cb").checked)
will evaluate to true for the above markup.
In contrast, with <input id="cb" type="checkbox" data-checked>, the "data-checked" attribute is reflected via the dataset object as a string. The value of this property is the empty string, which in JavaScript is falsey. So,
if (document.getElementById("cb").dataset.checked)
will evaluate to false for the above markup.
To do the equivalent test, compare the value for "not undefined". I.e.
if (document.getElementById("cb").dataset.checked !== undefined)
will evaluate to true for the above markup.
See http://jsfiddle.net/GAxvW/
Simple Boolean Test For Element Attributes
To expand on Alohci's excellent answer, the following is a simple, flexible way to test for a true boolean attribute value supplied using one of three standard HTML conventions: <foo data-bar/>, <foo data-bar="true"/>, or <foo data-bar="data-bar"/>.
var a = elem['data-bar'];
var aTrue = ( a != null && a !== false && a !== 0 && a.charAt(0) != 'f' &&
a.charAt(0) != 'n' );
With the code above, the value is false if undefined or set to one of: f*, n*, 0 (case-insensitive), and true if defined and set to one of: (empty string), (attribute name), (anything else).
Empty strings are evaluated to true here because HTML attributes without values are '' which equal false in JS (and something like <foo disabled/> should equal <foo disabled="true"/>). You can use the above code for more general string testing by removing != null && a !== false.