Having problem taking input and outputting it into an HTML file - javascript

Trying to write a JS/HTML program that takes the user's name as an input and outputs "Hello, [Name]!" when you click he button.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>
JS:
let txtName = document.querySelector('#txtName');
//let name = "lauren";
function sayHello() {
document.write("Hello, " + txtName + "!");
}
When I try to run it, it outputs "Hello, null!" everytime.

Move it to the function itself and add "value":
function sayHello() {
let txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}

Your function does not have access the the txtName variable. You should move it inside the function. You can also use getElementById instead of a query selector. Since were there, why not remove the variable entirely:
function sayHello() {
document.write("Hello, " + document.getElementById('txtName').value + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>

Your code had 2 problems with it. One is scope and the other is value.
let txtName
As the variable is initiated using let, its scope is limited and not global. Use var to make it global, so it can get access inside functions too.
let txtName = document.querySelector('#txtName');
This line of code is running as soon as the page loads. So it is assigned the input object as the page gets loaded (and not the value). For printing the name, although we need the value of this object, (which is the second point) and not the whole object itself. We access its value by using .value.
var txtName = document.querySelector('#txtName').value;
Define this line inside the called function else it will get null value, because it will run as soon as the page loads and null value will be assigned because no input is there inside the input box.
function sayHello() {
var txtName = document.querySelector('#txtName').value;
document.write("Hello, " + txtName + "!");
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Greeter</title>
</head>
<body>
<script src="app.js"></script>
<input id = "txtName" placeholder="Your Name"/>
<button onclick="sayHello()"> Say Hello </button>
</body>
</html>

Related

Basic JavaScript how to call a function from the HTML page

I have just started JavaScript basics and I'm struggling with this:
HTML page has the following:
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
This page should call the function calcSquare(), which fetches the value of the element, calculate its square, and print in the console: The square of 5 is 25. The HTML page loads the code, so I can refer to the page with the document keyword. My js code is following:
function calcSquare() {
var number = document.getElementById("number").value;
console.log("The square of" + number + "is" number*number);
}
Can someone tell me what is wrong with it? Thank you so much! Beginners struggles...
The problem is with your function itself.
Keep in mind that .value is used with an input element. So you can use .innerHTML or .textContent.
You forgot also the sign + after "is".
Look at this code snippet .
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
<script>
function calcSquare() {
var numbElementcontent = document.querySelector('#number').innerHTML;
numbElementcontent = parseInt(numbElementcontent);
console.log("The square of " + numbElementcontent + " is " + numbElementcontent * numbElementcontent);
}
</script>
</body>
</html>
Instead of .value use .innerHTML, and you are missing sign + after "is"
You need to get textContent, and make some changes in your function calcSquare()
function calcSquare() {
var number = document.getElementById("number");
var number = number.textContent;
console.log("The square of" , number , "is" , number*number);
}
<body>
<p id="number">5</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
And if you are use an input-field you make it more dynmaic :) and if the is target an input you can use the .value
Be sure you cast every time your vars into the right type before do math (parseInt, parseFloat etc)
And because you are new on JS please deal with JS Security - it is very important for your future dev..
https://snyk.io/learn/javascript-security/
https://glebbahmutov.com/blog/disable-inline-javascript-for-security/
Try this . Foe elements such as P or Div You have to ue textContent or innerHTML to get the data inside the tag. You missed string concatenation after "is" too
function calcSquare() {
var number = document.getElementById("number").textContent;
console.log("The square of" + number + "is" +number*number);
}
<body>
<p id="number">6</p>
<button id="buttonX" onclick="calcSquare()">Click here!</button>
</body>
<script>

How to get the value inside the input of type text in JavaScript?

var data = document.getElementById('myFieldId');
console.log(data.value);
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>
I expect when I write any text in the input, it would print the corresponding text. But I don't get anything in the console. What should I do?
You need to add an event listener that executes as soon as someone inputs text.
There is no such thing as binding a variable to a text input; this needs to be implemented by yourself.
See this example:
const data = document.getElementById('myFieldId');
data.addEventListener(
'input', // first argument is the name of the event you want to react to
// second argument is the function that should execute when the event occurs
function(inputEvent) {
console.log(data.value);
}
);
<input type="text" id="myFieldId"/>
You code start at load page so is empty, i add an onchange event so when you finish to write console.log will output the value.
var data = document.getElementById('myFieldId');
data.onchange = function()
{
console.log(this.value);
};
<!DOCTYPE html>
<html>
<head> </head>
<body>
<input type="text" id="myFieldId"/>
<script src="main.js"></script>
</body>
</html>

Displaying input back to a user - javascript

I have found several questions with answers on how to do this, but I think my problem is an interesting one. I am trying to have a user enter in their name in a text box, then once they hit a button it will display it back to them.
This is the code I have:
<html>
<head>
<title>Side Bar test</title>
<link rel="stylesheet" href="test.css" />
</head>
<body>
<div id="sideWrapper">
<p id="wrapper"><label for="name">Name: <input type="text" name="name" id="name"></p>
<button onclick="display();">Submit</button>
</br>
<div id="playerName">
</div>
</div>
</body>
<script type="text/javascript" language="javascript">
var input = document.getElementById("name").value;
function display() {
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
When the document.getElementById("name").value is called, it only takes whatever was in the text field when the page first loaded. Trying to update it after and clicking the button doesn't work. So, if you type "John Doe" in the field and then reload the page and hit the button, it will display John Doe. But if you try to change it, it doesn't work. I have tried moving the script to the <head> but that only makes it undefined.
How can I make it so the display() function sees what the user types in the box and updates it to print it out to the screen?
EDIT: Fixed the code by moving the input line into the function body.
<script type="text/javascript" language="javascript">
function display() {
var input = document.getElementById("name").value;
document.getElementById("PlayerName").innerHTML = "<p>Player: " + input + "</p>";
}
</script>
You need to put your declaration of input inside your display function.
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
As you currently have it, the value of input is stored when the page is loaded, so it does not update automatically.
You're problem is that this: var input = document.getElementById("name").value;
fires immediately when the program loads.
To fix this, do this:
function display() {
var input = document.getElementById("name").value;
document.getElementById("playerName").innerHTML = "<p>Player: " + input + "</p>";
}
That way, the input variable is assigned the current value of the input element each time the function is called.
Here is a fiddle to show that the input variable assignment fires when the page is loading. I added a default value to the input to show that no matter what you change it to afterwards, the value is always what the default is.
The input = document.getElementById("name").value; should be inside the function display(), because you will always set it it's initial value (empty).

Web-browser is not showing the output

I'm new to JavaScript and already encountered a problem. When I run the code and the browser pops up, it[browser] does not show anything. What I have is the testMethod.js file with one method:
function testMethod(num1, num2){
var value = num1 + num2;
return value;
}
and an HTML file from where I'm trying to run:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> My JavaScript</title>
<script language = "javascript" src = testMethod.js"></script>
</head>
<body>
<script language = "javascript" type = "text/javascript">
// var getValue = testMethod(2,3);
document.write("The result is " + testMethod(5,3));
</script>
<noscript>
<h3> This site requires JavaScript</h3>
</noscript>
</body>
</html>
The code is not implementing the result at all. It shows only a blank page browser.
It seems you have a quote missing in the html, it should say src="testMethod.js" where you are including the script in the first place.

Issue with getElementById

I have written the following code to display an input with Javascript's alert( ... ) function.
My aim is to take a URL as input and open it in a new window. I concatenate it with 'http://' and then execute window.open().
However, I just get 'http://' in the URL name, even after concatenation, and not the complete URL. How can I fix this?
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<body onload="onload();">
<input type="text" name="enter" value="" id="url_id">
<input type="button" value="Submit" onclick="func();">
</body>
<script type="text/javascript">
var url;
function onload() {
url = document.getElementById("url_id").value;
}
function func(){
var var1 = "http://";
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
</script>
</head>
</html>
You shouldn't be calling it in onload(), only after the user has entered the url into the input field. Of course its an empty string, because you assign url to the value of #url_id before the user has a chance to enter anything when you place it in onload().
function func(){
var var1 = "http://";
url = document.getElementById("url_id").value;
var var2 = url;
var res = var1.concat(var2);
alert(var2);
//window.open(res);
}
Others have given solutions, and you already have accepted one. But none of them have told you what is wrong with your code.
Fristly, you have a body element inside your head element. This is invalid markup. Please correct it:
<html>
<head>
<!-- this is a script -->
<script type="text/javascript">
// javascript code
</script>
</head>
<body>
<!-- this is an inline script -->
<script type="text/javascript">
// javascript code
</script>
</body>
</html>
Secondly, you need to have an idea about the execution order of JavaScript inside browser windows. Consider this example:
<html>
<body onload="alert('onload')">
<p>Lorem Ipsum</p>
<script type="text/javascript" >
alert('inline');
</script>
</body>
</html>
Which alert do you thing will get executed first? See the JSFiddle.
So as you can see, inline JavaScript will be executed first, and then the browser will call whatever code is in <body onload=.
Also, onload function is called immediately after the page is loaded. And user has not entered anything when the function is executed. That is why you get null for url.
function func()
var url = document.getElementById("url_id").value;
var fullUrl = "http://".concat(url);
alert(fullUrl);
// or window.open(fullUrl);
}
You're not concatenating with a String but with an Object. Specifically an HTMLInputElement object.
If you want the url from the text input, you need to concatenate with url.value.
if its not concatenating, use:
var res = val1+val2.value;

Categories

Resources