Declaring variables and using getElementById to print Hello World - javascript

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>

Related

Why Javascript Event Handler only works on the HTML page? [duplicate]

<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image);
var desc = document.getElementById(desc);
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiD.jpg"]
var descs = ["1", "2"]
var num = 0;
var total = images.length;
function clicked(){
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById(submit).onclick(clicked());
</script>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
</html>
The line "document.getElementById(submit).onclick(clicked());" throws an error
"ReferenceError: submit is not defined"
When I tried accessing buttons in general
[through getElementsByClassName & getElementsByTagName]
it gave an error of "ReferenceError: button is not defined"
Using strings in getElementById it throws the error "getElementById is null"
I found several questions and answers to this.
Only one of them I understood how to implement, due to the use of PHP and that being the error on most others. Other solutions I found involved errors numerically.
On this error I tried a fix of printwindow.document.getElementById(..etc
This gives me an error of "ReferenceError: printwindow is not defined"
Browsers run JavaScript as soon as possible in order to speed up rendering. So when you receive this code:
<html>
<head>
<script type="text/javascript">
var image = document.getElementById(image); // Missing quotes, typo?
... in runs intermediately. There's no <foo id="image"> on page yet, so you get null. Finally, you get the rest of the page rendered, including:
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
It's too late for your code, which finished running long ago.
You need to bind a window.onload even handler and run your code when the DOM is ready (or move all JavaScript to page bottom, after the picture).
It should be document.getElementById('submit').onclick(clicked());
your must enclose the id you are searching for in quotes:
document.getElementById('ID_to_look_up');
You are executing javascript before your 'body' rendered. Thus document.getElementById("submit") would return null. Because there are no "submit" DOM element yet.
One solution is to move your javascripts under 'body', Or use JQuery with
$(document).ready(function() {
...
});
Your variable also has scope problem, your function cannot access variable declared outside this function with 'var' declaration. If you really need that variable, you should remove 'var' declaration.
A better way is to move all your variable inside clicked function. like following code
<html>
<head>
</head>
<body>
<div><h2>Project |</h2><h2> | herbykit</h2></div>
<div>
<button id="submit">Next</button><br/>
<img id="image" src="http://i.imgur.com/XAgFPiD.jpg" height="20%" width="50%"/>
<p id="desc">first desc.</p>
</div>
</body>
<script type="text/javascript">
function clicked(){
var image = document.getElementById("image");
var desc = document.getElementById("desc");
var images = ["http://i.imgur.com/XAgFPiD.jpg", "http://i.imgur.com/XAgFPiE.jpg"];
var descs = ["1", "2"];
var num = 0;
var total = images.length;
num = num + 1;
if (num > total){
num = 0;
}
image.src = images[num];
desc.innerHTML = images[num];
}
document.getElementById("submit").onclick = clicked;
</script>
</html>

How to extract variable from script tag in html blob

I am trying to figure out how to extract a variable from a giant string of html. A simplified example is below:
Update Here is a screen shot of trying to use the common approach called out below. Doing something as simple as test['foo'] doesn't work. This is a string returned from a server and is never loaded into the actual document or window. It's just an html object that's kept in memory.
https://jsfiddle.net/hvpvg3o4/
HTML
<div id="test"> <!-- div is just for jsfiddle -->
<script>
var test = { // <-- I WANT YOU!
foo: 'bar'
};
var somethingIDontWant = 1;
var iDontCareAboutYouEither = {
blag: 1 + 1
};
</script>
</div>
JavaScript
var testTag = document.getElementById('test');
var scriptTag = testTag.getElementsByTagName('script');
// var testObj = ?;
I was hoping that I could just get the text from the script tag and either run eval or some JSON.parse, but since there's other stuff within the script tag, I can't
Is there some way to extract a variable from a script tag or some fancy regex to do so?
Try this
console.log(test['foo'])
console.log(somethingIDontWant)
console.log(iDontCareAboutYouEither['blag'])
<div id="test">
<script>
var test = {
foo: 'bar'
};
var somethingIDontWant = 1;
var iDontCareAboutYouEither = {
blag: 1 + 1
};
</script>
</div>
If the object that is desired is declared in the global scope. The desired object will be accessible anytime a script tag is declared.
Example:
<HTML>
<HEAD>
<SCRIPT>
var test = {
foo: 'bar'
};
var somethingIDontWant = 1;
var iDontCareAboutYouEither = {
blag: 1 + 1
};
</SCRIPT>
</HEAD>
<BODY>
<DIV>UGLY HTML</DIV>
<SCRIPT>
//INSERT CUSTOM SCRIPT FOR ACCESSING DESIRED OBJECT//
console.log(test)
</SCRIPT>
</BODY>
</HTML>
The console can still access var test..even in later defined script in the body...
Output:
{foo: 'bar'}

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

strange behaviour of variable named "status" in 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"?

Enter variable name in textbox and get corresponding value

I have created 3 variables a,b,c. I have assigned values to a and b and have also made a textbox. What I want to do is enter the name of a the variable in the textbox and click the button, then the textbox should should display the value assigned to that variable. It maybe very simple but I do not know what I did wrong.
Here is the FIDDLE
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=c;
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
​
Your easiest choice would be to assign your variables to a object, like this:
var vars;
function display() {
var value = document.getElementById("b1").value;
vars = {
a: 2,
b: 3,
c: value
}
if (vars.hasOwnProperty(value)) { // If the entered value is a variable name
document.getElementById("demo").innerHTML = vars[value]; // Display the variable
} else { // Otherwise
document.getElementById("demo").innerHTML = value; // display the value
}
}
Working example
The if/else can be replaced with this, to make it a little shorter:
document.getElementById("demo").innerHTML = vars.hasOwnProperty(value) // If
? vars[value] // Then
: vars.c; // Else
Try this way:
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
if(c==a){
document.getElementById("demo").innerHTML='a';
}
if(c==b){
document.getElementById("demo").innerHTML='b';
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update value.</p>
</body>
</html>
DEMO
What you are looking for is the eval() method (Which, do a quick google search, it is not recommended).
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=(eval(c));
// if user enters b in the input field, then the html in demo will be 3
// if user enters a in the input field, then the html in demo will be 2
}
</script>
Again, not recommended!
If you declare variables directly in you script-element they are created as properties of the window-object and can be accessed as such. Thus just update your script like the following to show the contents of the variables:
<html>
<head>
<script>
var a = 2, b = 3;
function display() {
var strVarName = document.getElementById('b1').value;
if(window.hasOwnProperty(strVarName)) {
document.getElementById('demo').innerHTML = window[strVarName];
} else {
document.getElementById('demo').innerHTML = 'Variable ' + strVarName + ' does not exist.'
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
This won't work if you declare the variables inside the display function, but this doesn't seem like a thing you would do if this code were to be used in a system to anything beside this one simple function.

Categories