Displaying input back to a user - javascript - 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).

Related

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

How to I get the input from the HTML to link to the MyChecker function? It doesn't work

This is the code I used. It takes the first name and the surname from the user and then uses them in the MyChecker function where it matches up the names used to create different alerts. I can't get the MyChecker function to link to the values inputted by the user?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<p>What's your name?</p>
<form action="action.php"> //This form gets the input from the user
First Name
<br><input type="text" name="FirstName" value="" id="txt1"><br>
Second Name
<br><input type="text" name="SecondName" value="" id="txt2"><br>
<button onclick="myFunction()">Submit</button>
</form>
<script type="text/javascript">
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
var x= FirstName.localeCompare("Donald");
var y= SecondName.localeCompare("Trump");
MyChecker();
function MyChecker()
{
if(x==0&&y==0)
{
alert("I love the poorly educated");
}
var a= FirstName.localeCompare("Edward");
var b= SecondName.localeCompare("Snowden");
if(a==0 && b==0)
{
var ask=prompt("Would you mind collecting your cake from our office in Pennsylvania?","Choose between yes or no");
var cmp=ask.localeCompare("yes");
if(cmp==0)
{
alert("We'll even reimburse your plane tickets!");
}
else
{
alert("Perhaps next time...");
}
}
if(a!=0 && b !=0 && x !=0 && y!=0)
{
alert("Carry on...");
}
}
</script>
</body>
</html>
I touched up your indentation and hopefully it helps to expose the issue. When you submit the form, you will call myFunction, which I've copied here for clarity:
function myFunction() { //This function gets the values inputted by the user
document.getElementById('txt1').value);
document.getElementById('txt2').value);
}
... and that's it. These values aren't even saved.
You probably mean to have myFunction call MyChecker, so that your logic will be executed each time the form is submitted.
You might also consider having MyChecker take in the FirstName and SecondName as parameters, since myFunction is already reading values from the form.

Saving var using JavaScript and redirecting to URL

I have a very simple web form containing two input fields and a submit button.
What I would like to do is save the two strings inserted and redirect to my other HTML file (which is in the same folder).
HTML:
<!DOCTYPE html>
<html>
<title>Players enter</title>
<head>
<script type="text/javascript" src="ticTac.js"></script>
<link rel="stylesheet" type="text/css" href=styleSheet.css></link>
</head>
<body>
<form >
player one name: <input type="text" id="firstname"><br>
player two name: <input type="text" id="secondname"><br>
<input type="submit" onclick="checkNames();"/>
</form>
</body>
</html>
JavaScript:
function checkNames(){
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
//window.location.href = 'C:\Users\x\Desktop\hw3\tic\Game.html';
//window.location.replace("C:\Users\x\Desktop\hw3\tic\Game.html");
window.location.assign("C:\Users\x\Desktop\hw3\tic\Game.html");
}
I have commented the two other options I tried which also do not work.
You are using an HTML form... this means that your submit button will fire and try to submit your form.
In order to prevent this, you need to prevent that event from triggering. A simple modification to your JavaScript function should do the trick.
function checkNames() {
event.preventDefault();
var nameOne = document.getElementById("firstname").value;
var nameTwo = document.getElementById("secondname").value;
window.location.href = 'SOME-PATH/Game.html';
}
To redirect to a page in your computer you can use:
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html';
There are more than one way of passing the values to another page. Here is an example using query string.
In the page that has the values.
var q = '?nameOne=' + encodeURI(nameOne) + '&nameTwo=' + encodeURI(nameTwo)
window.location.href = 'file:///C:/Users/x/Desktop/hw3/tic/Game.html' + q;
In the page receiving the values.
var nameOne = location.search.slice(1).split("&")[0].split("=")[1];
var nameTwo = location.search.slice(1).split("&")[1].split("=")[1];
Use
window.location="url";

External JavaScript file issues

Now this is just for reference for a future project but I am trying to call a function that reads in a string but displays a float after. So I first check the string then display a random number. The problem I am having, I think, is with the document.getElementById part. Any suggestions??
HTML File:
<html>
<body>
<input type="text" id="letter" value=""/><br/>
<input type="button" value="LETS DO THIS!" onclick="floatNum();"/></br>
<script type="text/javascript" src="letNum.js"></script>
</body>
</html>
External JS File:
function floatNum()
{
var val1 = document.getElementById("letter");
if (isNaN(val1)
{
alert(Math.random())
}
}
the following code is working:-
in your code,you missed closing parenthesis ")" near to "if condition"
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>demo</title>
<script type="text/javascript">
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value))// using input fields value not the whole object
{
alert(Math.random());
}
}
</script>
</head>
<body>
<input type="text" id="letter" value="" /><br />
<input type="button" value="LETS DO THIS!" onclick="floatNum();" />
</body>
</html>
Yes, you want to pass in the element in the function, like so:
<input type="button" value="LETS DO THIS!" onclick="floatNum(document.getElementById('letter'))"/></br>
And in your JS
function floatNum(el)
{
if (isNaN(el)
{
alert(Math.random())
}
}
In case of a reusable function - try not to make it dependent on your DOM. Think about what would happen if you rename your element or want to use this function again. You couldn't before - now you can.
The problem is on this line:
var val1 = document.getElementById("letter");
It should be:
var val1 = document.getElementById("letter").value;
The first sets val1 to the DOM element representing the input tag, the second sets it to the text value of the input tag (its contents).
You need to process the value of input field not the input field itself.
function floatNum()
{
var letter = document.getElementById("letter");
if (isNaN(letter.value) // using input fields value not the whole object
{
alert(Math.random())
}
}
You don't grab the value of the input, but the input itself.
Correct code would be :
var val1 = document.getElementById("letter").value;

Retrieving user input and posting within HTML

I am looking at "HTML" and "JavaScript" and I have a prompt box that asks for the "users name", I was wondering if there's a way of then posting the name they have entered onto the webpage.
To give a bit of background I am creating a game and once the user has entered their name I would like to display it underneath a canvas that contains the game, alongside their score, here is what I have so far.
Code:
var player=prompt("Please enter your name");
if (player!=null)
{
x="Hello " + player + ;
document.getElementById("demo").innerHTML=x;
}
Change your opening body tag to this:
<body onload="placeName();">
Then, your JS file should look like this:
function placeName(){
var name = prompt("Enter name");
if (name != null){
var greeting = "Hello " + player + "!";
document.getElementById("demo").innerHTML = greeting;
}
}
You also need to make sure that you have a div or something of the sort with the id demo to actually change when the function runs. That's extremely important. The only thing that's different above from what you did is that it waits until the body loads to prompt the user. Your JS file may have loaded before your document, which could cause issues. Also make sure that you have linked your JS file to your HTML file or have put it in script tags in the head. If none of that works, check your console for errors and put it in a JSFiddle so that we can see all of your code to check for errors.
try this:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x;
var person = prompt("Please enter your name", "Harry Potter");
if (person !== null) {
x = "Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML = x;
}
}
</script>
</body>
</html>
from http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_prompt

Categories

Resources