Retrieving user input and posting within HTML - javascript

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

Related

Google App Script Bounded to Spreadsheet

what I' trying to accomplish is a Google Spreadsheet for a project management. I've got lots of cells in a grid where a user should select either the item was completed or not. Now this spreadsheet would be available only to a Project Manager. The way I imagined the process would work was that Project Manager selects particular cells and assigns them to a technician's email address. Script would then generate mobile friendly html UI and send it to the technician (I thought of Google forms but I want to create more customized UI). Technician would then select a checkbox after completing a task which would at the same time update the spreadsheet. Next time technician would open the UI it would populate all the checkboxes that previously were selected.
The only way I've found that I could make it work was a google script web app bounded to a spreadsheet. I've created a test HTML file and .gs file:
.html file
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<h1> Web App Test </h1>
<input type="button" value="Click Me" id="buttonclicked" onclick="getSomeData()"/>
<div id="output" class="current">output</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function getSomeData()
{
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(showError)
.testForWebApp();
myLog("in WebAppTest.html getSomeData()");
}
function onSuccess(testParam)
{
var div = document.getElementById('output');
if (sectionName == null)
div.innerHTML = "<p style='color:red;'>You didn't hit the script</p>";
else
div.innerHTML = "<p style='color:white;'>" + testParam + "</p>";
}
function showError()
{
var div = document.getElementById('output');
div.innerHTML = "<p style='color:red;'>You didn't hit the script</p>";
}
</script>
</body>
and .gs file:
function doGet()
{
return HtmlService.createHtmlOutputFromFile('WebAppTest')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function testForWebApp()
{
myLog("In testForWebApp()");
var msg = "Yep you hit the script!";
return msg;
}
function myLog(log)
{
//log = 'test';
Logger.log(log);
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('log');
var lastRow = sheet.getLastRow();
sheet.insertRowBefore(1);
var newLogDateRange = sheet.getRange(1, 1);
var newLogTextRange = sheet.getRange(1, 2);
var now = new Date();
newLogDateRange.setValue(now);
newLogTextRange.setValue(log)
}
When I published the app and followed the generated link I saw my html page with a Click Me button. The click event ran the getSomeData() function which called google.script.run function. The server side .testForWebApp() gotten executed because I've gotten a log entry from myLog() but the .withSuccessHandler or .withFailureHandler were never called. At the same time the myLog() that should be executed after google.script.run never run either.
I definitely don't understand how it works and suspect that if I publish a script as a web app the HTML is not bounded to the script anymore, but I couldn't find any information about it online.
Thanks for your help.
Firstly, you cannot call server-side myLog() function from your client side javascript unless you call it using google.script.run.myLog() Therefore
myLog("in WebAppTest.html getSomeData()");
in your getSomeData() doesnt log anything in your google sheet
Secondly, this code in function onSuccess(testParam)
if (sectionName == null)
is causing your function to terminate prematurely, since there is no variable called sectionName defined.
Note: You can monitor all these errors in the console of your web browser.
Below is the modified code that should work as you intend it to
Final code:
Web App Test
output
function getSomeData()
{
google.script.run
.withSuccessHandler(onSuccess)
.withFailureHandler(showError)
.testForWebApp();
console.log("in WebAppTest.html getSomeData()"); //Log it on the browser console
}
function onSuccess(testParam)
{
var div = document.getElementById('output');
if (testParam == null) // Changed it to testParam from sectionName, to check the value returned from testWebApp()
div.innerHTML = "<p style='color:red;'>You didn't hit the script</p>";
else
div.innerHTML = "<p style='color:black;'>Success:" + testParam + "</p>";
}
function showError()
{
var div = document.getElementById('output');
div.innerHTML = "<p style='color:red;'>You didn't hit the script</p>";
}
Edit
One last note, the below code would make the return text invisible as the text and background color would be the same color (white):
div.innerHTML = "<p style='color:white;'>Success:" + testParam + "</p>";
hence changed the text color to black in the final code
Hope that helps!
Try redeploying the web app, but under a new project version.

Trying to validate JavaScript input using OnClick and a function. No matter what is entered, it says the format is correct.

I have an HTML file and an external JavaScript file. I have input from the user in the HTML and on the click on the validate button, the courseValidation() function is called. The problem is with the if statement. When the input does not match myRegExp, it should write that the format is incorrect to the page, but it always writes Correct Format, regardless if it is correct or not. Not sure what I am doing wrong. I'm just learning so no negative comments please.
HTML File:
<html lang="en">
<head>
<title>Validation</title>
</head>
<body>
<script src="course.js"></script>
<p>Enter Course Information:</p>
<input id="courseCode" type="text">
<button onclick="courseValidation()">Validate</button>
<p id="course"></p>
</body>
</html>
External JavaScript File:
function courseValidation() {
var courseCode = document.getElementById("course").innerHTML;
var myRegExp = /\D{3}.\d{3}#\d{4}_\D{2}-\d{4}/;
if (courseCode.match(myRegExp)) {
document.write("Incorrect Format");
} else {
document.write("Correct Format");
}
}
You are not retrieving the value of the input correctly. var courseCode = document.getElementById("course").innerHTML; should be var courseCode = document.getElementById("courseCode").value;.
Also, your if statement is the wrong way around. It should read:
if (courseCode.match(myRegExp)) {
document.write("Correct Format");
} else {
document.write("Incorrect Format");
}
The ID of your input is courseCode not course and you are using .innerhtml, it should be .value
var courseCode = document. getElementById('courseCode).value

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).

How do I use this JavaScript variable in HTML?

I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
You can create a <p> element:
<!DOCTYPE html>
<html>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
p = document.createElement("p");
p.innerHTML = "Your name is "+lengthOfName+" characters long.";
document.body.appendChild(p);
</script>
<body>
</body>
</html>
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.
The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.
There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).
Examples for both options:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
<p id="a"></p>
<p id="b"></p>
<script>
document.getElementById('a').innerHTML = name;
document.querySelector('#b').innerHTML = name.length;</script>
</body>
You could get away with something as short as this:
<script>
const name = prompt("What's your name?") ?? "";
document.write(`<p>${name.length}</p>`);
</script>
It's not a very clean way of doing it but using document.write is not much worse than calling prompt() as soon as the page loads.
A more user-friendly approach would be to have an actual text input on the page and to dynamically update the length as they type using an event listener.
<label>Name: <input id="name-input"></label><br>
Length: <output id="name-length-output" for="name-input">0<output>
<script type="module">
const nameInput = document.getElementById("name-input");
const nameLengthOutput = document.getElementById("name-length-output");
nameInput.addEventListener("input", e => {
nameLengthOutput.textContent = nameInput.value.length;
});
</script>
If you want to learn how to manipulate pages with JavaScript, the Mozilla Developer Network has a good tutorial about the DOM.

function write(message) not working

I'm doing the PluralSight JavaScript Fundamentals course and he enters this code into the JavaScript window of jsbin (jsbin.com)
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick";
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
and when he Previews it writes out the types and values. The video is a year old and now jsbin has a Render (not Preview) button. When I enter the above code and Render I get a blank screen.
I tried pasting the code into an .html file
<!DOCTYPE html>
<html>
<head>
<!--<meta charset=utf-8 />-->
<title>JS Test</title>
</head>
<body>
<p id="hello">Hello World</p>
<script>
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
var streetNumber = 49;
var streetName = "Brunswick"';
write(typeof streetNumber + " " + streetNumber);
write(typeof streetName + " " + streetName);
</script>
</body>
</html>
and then opened the file in IE9, and the latest version of Chrome, Firefox, Safari and Opera (my OS is Win7 Ult). They all display Hello World and nothing else. I'm probably missing something really simple here, can someone help me out?
You don't have a message element. Change the #hello element to #message.
<p id="hello">Hello World</p>
To this
<p id="message">Hello World</p>
This is what is needed for the getElementById code to have a place to print your output. Without an element having the requested ID, nothing will turn up, and hence nothing will be printed.
You have a syntax error as well:
/* v----- This little guy here doesn't belong. */
var streetName = "Brunswick"';
Note the umatched single quote at the end of this string. Remove that and you should be good to go:

Categories

Resources