strange behaviour of variable named "status" in javascript - javascript

<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var status = [true,false,true,false,true,false,true,false,true,false];
var status1 = [true,false,true,false,true,false,true,false,true,false];
document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>
</body>
</html>
https://jsfiddle.net/vdr2r38r/
Why is the behavior different for identical variables with different names?

It's because you run your code in global context! var bound variables are bound to the function scope. If you have no function you are in global context, which means in a browser you are on the window object.
This code will log Demo:
<script>
var foo = "Demo";
console.log(window.foo);
</script>
Now your code breaks because window.status is reserved.
An easy fix is to surround your code by a function to provide a new context for your variables, which is always good practice.
<script>
(function() {
var status = [true,false,true,false,true,false,true,false,true,false];
var status1 = [true,false,true,false,true,false,true,false,true,false];
document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
})();
</script>

The word status is a reserved keyword, so you need to rename it like status3 or something else. See snippet below. You can also see a list of reserved words by visiting this link: http://www.w3schools.com/js/js_reserved.asp
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
var status3 = [true,false,true,false,true,false,true,false,true,false];
var status1 = [true,false,true,false,true,false,true,false,true,false];
document.getElementById("demo1").innerHTML = status3[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>
</body>
</html>
I hope this will help you.

change variable name 'status' , it is a Windows Reserved Word.
In HTML you must avoid using the name of HTML and Windows objects and properties

ES6 / ES2015 solution
Use let or const when declaring your global variables. They do not get defined on the window object. Therefore, clashes with window.status or window.name and other properties of the global object can be avoided.
Demonstration below:
let
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let status = [true,false,true,false,true,false,true,false,true,false];
let status1 = [true,false,true,false,true,false,true,false,true,false];
document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>
</body>
</html>
const
<!DOCTYPE html>
<html>
<body>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
const status = [true,false,true,false,true,false,true,false,true,false];
const status1 = [true,false,true,false,true,false,true,false,true,false];
document.getElementById("demo1").innerHTML = status[2];
document.getElementById("demo2").innerHTML = status1[2];
</script>
</body>
</html>
See also What's the difference between using "let" and "var"?

Related

Declaring variables and using getElementById to print Hello World

The assignment is such that I have to declare variables 1(Hello), 2(world) and result, and create a string in p element using getElementById/innerHTML. The result should also printed in console log. I've tried several combinations such as this, but I have no idea how to go from here.
<!DOCTYPE html>
<html>
<body>
<p id= "tulos">Haloo maailma!</p>
<script>
var tulos = document.getElementById("tulos").innerHTML "Haloo";
var tulos = document.getElementById("tulos").innerHTML = document.getElementById("tulos").innerHTML+ "maailma!";
console.log(tulos);
</script>
</body>
</html>
im not sure what do you need, but my guess is you want to print variable to a p tag and also able to console it
<p id="target"></p>
<script>
let var1 = 'hello';
let var2 = 'world';
let result = var1 +' '+var2;
let target = document.getElementById('target');
target.innerHTML = result;
console.log(result);
</script>

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

Printing object property in an html paragraph

I should get an output of "Peter" in the paragraph with id="para1", but somehow, this is not happening. Can someone help me out?
<html>
<head>
</head>
<body>
<p id=para1></p>
<script>document.getElementById('para1').innerHtml = alpha.name;</script>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
</script>
</body>
</html>
I've changed the code to this, still cannot see the word "Peter" in the html screen:
<html>
<head></head>
<body>
<p id=para1></p>
<script>
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHtml = alpha.name;
</script>
</body>
</html>
There are two mistake you have.
First: <p id=para1></p> id must have " like <p id="para1"></p>
Second: innerHTML not innerHtml
Check your updated code here:
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
<p id="para1"></p>
Your main mistake is innerHtml instead innerHTML. But all your code is not good formatted.
Let's change your code
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
You're trying to call the object before it exists. Either change your script around, or use window.onload:
<script type="text/javascript">
window.onload = function(){
var alpha = {name:"Roshan",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
};
</script>
This makes sure that the page is fully loaded before the scripts gets executed.
This is by far the best and safest solution, but if you rather leave it to "load as you go", then changing the order would (perhaps) be sufficient:
<p id="para1"></p>
<script type="text/javascript">
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
Edit:
Also, as others mentioned - it's .innerHTML. Javascript is case sensitive.
<html>
<body>
<p id="para1"></p>
<script>
var alpha = {name:"Peter",age:23,gender:"male"};
document.getElementById('para1').innerHTML = alpha.name;
</script>
</body>
</html>

javascript function object prototype

Why prototype function is not called .. when image is clicket?
Html Code :--
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<script type="text/javascript" src="tt.js"></script>
</head>
<body>
<p>This example calls a function which performs a calculation, and returns the result:</p>
<p id="demo"></p>
<input type="image" src="http://t2.gstatic.com/images?q=tbn:ANd9GcSTcJA5J-LOj0HOP1ZMzdSQIsxwuguFdtlesHqzU15W8TXx232pFg" onclick="myFunction('Info clicked')"/>
<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>
</body>
</html>
java script :--
function myFunction(l) {
this.k = "hello";
alert(this.k);
var t = this.temp(l);
alert(t);
}
myFunction.prototype.temp = function(a)
{
alert(a);
return 10;
}
If i put inside html page body it works :--
<script>
var a = new myFunction();
document.getElementById("demo").innerHTML = a.k;
</script>
Because you are calling this.temp() on the constructor function and not on an instance of it.
You need to create an instance with new.
new myFunction('Info clicked')
Note that this doesn't make sense. If you want to do things when the constructor runs, you should assign the methods to the constructor and not the prototype.
If you want to stick to your javascript definition, all you need to do to solve this problem is to change the attribute onClick on your html code to new myFunction("...");
<input type="image" src="http://..." onclick="new myFunction('Info clicked')"/>

Javascript variable access in HTML

Say I have the following JavaScript in a HTML page
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
</script>
<body>
<a href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
How do I get the value of the variable "splitText" outside the script tags.
Thanks!
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myLink").innerHTML=splitText;
}
</script>
<body>
<a id="myLink" href = test.html></a>
</body>
</html>
Try this :
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
$("#target").text(splitText);
});
</script>
<body>
<a id="target" href = test.html></a>
</body>
</html>
<html>
<head>
<script>
function putText() {
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
}
</script>
</head>
<body onLoad = putText()>
<a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>
In raw javascript, you'll want to put an id on your anchor tag and do this:
<html>
<script>
var simpleText = "hello_world";
var finalSplitText = simpleText.split("_");
var splitText = finalSplitText[0];
function insertText(){
document.getElementById('someId').InnerHTML = splitText;}
</script>
<body onload="insertText()">
I need the value of "splitText" variable here
</body>
</html>
Here you go: http://codepen.io/anon/pen/cKflA
Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ
The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph).
Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.
Example:
<!DOCTYPE html>
<html>
<body>
<!--\|/id here-->
<p id="myText"></p>
<p id="myTextTag"></p>
<script>
<!--Here we retrieve the text and show what we want to write...
var text = document.getElementById("myText");
var tag = document.getElementById("myTextTag");
var toWrite = "Hello"
var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"
<!--...and here we are actually affecting the text.-->
text.innerHTML = toWrite
tag.innerHTML = toWriteTag
</script>
<body>
<html>

Categories