I'm following w3school beginner tutorial for JS. There's something I don't understand from code below:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["Saab","Volvo","BMW"];
var text = "";
for(var i = 0; i < cars.length; i++) {
text+=cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Can someone explain me the logic of text+=cars[i]? I understand that += means increment, but I can´t understand the logic behind adding the array element to variable text.
Thank you so much for your quick replies! I've got a follow up question: is there an alternative to display the same type of information with having to use the
var text = "";
and
text+=cars[i]
pieces of code? If so, how would the snippet of code look like and what should I insert into HTML if not
text
?
Thanks again!
a+=b is short for a=a+b. In your case you have text = text + cars[i] + "<br>".
text is a string, and you are using + to append a value from the array (that contains strings), and then append "<br>"
The value of text at the end of the loop is going to be
Saab<br>Volvo<br>BMW<br>
where br stands for line break. So that each of them gets printed on new line.
And the last line of code
document.getElementById("demo").innerHTML = text;
changes the value of html element which has id of demo to that of text.
text += cars[i] + '<br>';
Concatenates element i of the cars array to the text, separated by a <br> tag.
Consider it like this,
text+=cars[i] + "<br>";
is actually
text=text+cars[i]+"<br>";
so that rather than deleting the old value it will concatenate the new word with existing string.(String Concatenation).
PS:As a fellow beginner a small piece of advice rather than following W3 Schools please go to site like codecademy which helps you to learn along with practice and proper explanation.
Don't think of += as incrementing, that's ++.
a = a + b
a += b;
Those two statements are the same. The bottom one takes the variable on the left side (a) and appends the right side to it (b), and then assigns it all back to he left side (a). So it's just a shorthand.
So what you're doing in your code is appending the string from cars[i] to your variable text.
This would do the same thing:
text = text + cars[i] + "<br>";
Once the loop runs, you will have the following in text:
Saab<br>Volvo<br>BMW
In javascript + is used for string concatenation
The code
for(var i = 0; i < cars.length; i++) {
text+=cars[i] + "<br>";
}
is picking each element from the array and concatenating "" to it.
If you console log the text before setting the innerHTML, it looks something like this -
"Saab<br>Volvo<br>BMW<br>"
here they do it actually just to show theres no point of doing it this way they just wanna show to reach each individual inside an array and concatanate it into a string the very same thing you can do with Array.prototype.join() method dont think here that u must use as they show always concatanate into a string if you want you can simply use every single individual inside as u wish as well
+= is not increment. It's adding (in this case concatenation) and saving result in the same variable.
var a +=b;
Is the same to:
var = a + b;
In your case script concatenates all array elements into one string and adding <br> tags between them.
Related
Below as you can see in my code i created a input field for users that i want to store inside of an array, which also i want to store that array into localstorage. Now i think that stored the values that i give trough the input field in localsorage , beacuse that i can see from my browser application in chrome. Now with this code i have some problem.
Each value that i add one by one as you can see in the picture below ,whenever i refresh the browser , the values disapear from the browser?
So if someone can help me out with my code i would appriciate a lot , and also give me some advice , since im very new to localstorage and cookies and i am trying to learn
<input type="text" id="username"><br><br>
<input type="submit" id="btn">
<p id="demo"></p>
<script>
var btn=document.getElementById("btn");
var user=document.getElementById("username");
var names=[];
btn.onclick=function(){
names.push(user.value);
localStorage.setItem("names",JSON.stringify(names));
var f =JSON.parse(localStorage.getItem("names"));
var x;
var i;
for(i=0;i<f.length;i++){
x+=f[i]+"<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>
You're getting undefined because you never assign a value to x prior to using it in x+=f[i]+"<br>", so it gets the default value undefined, which is then converted to string. Assign "" to x before the loop.
Side note: There's no need for f in that code at all. Just use names:
localStorage.setItem("names",JSON.stringify(names));
var x = "";
for (var i = 0; i < names.length; ++i) {
x += names[i] + "<br>";
}
You might also consider using join instead of a loop:
localStorage.setItem("names",JSON.stringify(names));
var x = names.join("<br>");
Beware that if any name is entered that contains a < or &, it could potentially mess up your output, since of course those characters start things that are special in HTML (tags and character references, respectively). To prevent that, you might use map before join:
localStorage.setItem("names",JSON.stringify(names));
var x = names.map(function(name) {
return name.replace(/&/g, "&").replace(/</g, "<");
}).join("<br>");
or in modern JavaScript:
localStorage.setItem("names",JSON.stringify(names));
const x = names.map(name => name.replace(/&/g, "&").replace(/</g, "<"))
.join("<br>");
That's only valid if you're outputting to an element's body, as you are in that code; if you were outputting to an attribute value, it would be more complicated. (Some folks would also change > to >, but there isn't any need to if, again, you're outputting to the body of an element and not within a tag.)
I am doing a simple assignment for one of my modules and I've come into this problem for the 3rd or 4th time. My problem is that as my code shows below when I put the .innerHTML attribute on the first line it does not work at all and there is no error in the console window. When I place the it after the info.innerHTML on the second line it does work. I have asked a tutor and he is stuck on why this is happening
var info = document.getElementById("pOutput").innerHTML;
info = "Sum: " + sum + "<br>Average: " + avg;
var info = document.getElementById("pOutput");
info.innerHTML = "Sum: " + sum + "<br>Average: " + avg;
The second variation that you've included is correct but needs getElementById() instead of GetElementById().
The top lines are incorrect because you are overriding the variable info with your string, not writing it into innerHTML.
When you set info to innerHTML, it's getting the value. You need to set info to document.GetElementById("pOutput"), and then set info.innerHTML:
var info = document.getElementById("pOutput");
info.innerHTML = "Sum: " + sum + "<br>Average: " + avg;
The reason why this is happening is because in the first bit of code, you capture the value of the innerHTML property of the element. For example, if your element has <div></div> inside it, the value of info will be "<div></div>". If you modified the innerHTML of the element after, the value of info would still be <div></div>. On the contrary, in the second bit of code, what you capture is a reference to the element. Therefore you can modify its properties and it will reflect on the element itself. The reason why this happens is explained here but to make it simple, some types (like strings and numbers) are copied as values and some other types (like Objects) are copied as references.
I'm prefacing this with the fact that coding is most definitely not my strong suit.
I'm currently trying to join two pieces of text to form a link sitting behind an image. The first piece of text is defined (https://www.example.mystore.com/customers/) with the second part being from a datatable (<span id="customcontent752">[Link ID]</span>). Question is - how do I get both of these pieces of information to join to form
https://www.example.mystore.com/customers/[Link ID]? I figure it's something simple I can drop into the source code, but can't for the life of me work it out.
Cheers in advance!
var firstPiece = "https://www.example.mystore.com/customers/";
var secondPiece = $("#customcontent752").text().trim();
var result = firstPiece + secondPiece; //"https://www.example.mystore.com/customers/[Link ID]"
Simply use the + operator if both are strings.
i.e
"https://www.example.mystore.com/customers/" + link_id
should get you what you want.
you can use concat :
var x = "https://www.example.mystore.com/customers/"
var y ="[link ID]"
var result = x.concat(y)
I'm only just learning javascript so I imagine this is relatively simple but it's been annoying me for a while now.
I have a function that simply displays some text that I am calling from a AJAX response. Here's my code.
if(this.responseText != null)
{
var text = "<ul>";
var object = eval("(" + this.responseText + ")");
var track;
for (var i = 0; i < object.length; i++)
{
track = object[i];
text += "<li><img src=\"" + track.artwork_url + "\"/>";
text += track.title;
text += "<ul><li>Play</li>"
text += "<li>Download</li></ul>"
text += "</li>";
}
text += "</ul>";
document.getElementById("content").innerHTML = text;
}
function playTrack(track)
{
document.getElementById("content").innerHTML = "This has worked";
}
It's not liking me passing the track object to the function playTrack (a simple function for now that just displays some text). I get the error "Uncaught SyntaxError: Unexpected identifier"
If I pass in track.id (or any other property), it all works fine which I don't understand.
Thanks for any help,
Mister B.
You cannot pass an object like this. track is getting converted to a string and then your playTrack function call fails because the syntax is wrong. It'll be rendered (something like onclick=playTrack([Object object]) which clearly isn't valid JavaScript). What's wrong with just passing the track.id since you know that works?
The #alpian and #Jim is right, you need convert the object to json string, you can use http://www.json.org/js.html to this.
...
text += "<ul><li>Play</li>"
...
When creating the "playTrack" onclick event, you are using the track variable in the wrong way. "track" is an object, and using it as a string will be [Object object]. So in your "html" you'll have something like onclick="playtrack([Object object])" and this is syntactically wrong.
I'd strongly suggest the use of JSON.parse() instead of eval. Instead of building your list entries as text I'd make them as DOM objects with document.createElement() and add the click handlers as addEventListener, that way you wouldn't have the need to try to include your JS objects as text in the HTML stream.
I have already asked this question in offical Flot google groups, but got no answear. Maybe because it is more javascript oriented, here is the question:
I have added the following code in my code:
var j = "d";
j = j.sub();
plot1 = $.plot($("#grafTemp"), [
{label: "Rosišče (°C): T" + j + "(t) = ---.---°C"
.... the rest does not matter.
And:
legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2) +"°C"));
I was using this example:
http://people.iola.dk/olau/flot/examples/tracking.html
Now, the subscript works ok, it displays T_d fine. But when I update
the graph (when user moves mouse over graph), then it displays
<sub>d</sub>
I know that the problem is at the legends.eq(i).text....., where
it returns pure string, with literal:
<sub>
I would like to know, how it would be possible to fix this issue. So it would use html element sub properly?
Glancing at the code, it looks like you'd replace the use of text (e.g., legends.eq(i).text(...)) with html (legends.eq(i).html(...)). But you'd need to be sure that there aren't other generated bits of it that would be a problem (for instance, if this stuff generated a string that had a < or & in it, that would need to be converted to < / & respectively before being fed into the html function).