How to save user input into a variable in html and js

Hamzah Malik picture Hamzah Malik · Jul 2, 2013 · Viewed 211.1k times · Source

i am making a game and at the start it asks for your name. I want this name to be saved as varible. i have this html code:

<form id="form" onsubmit="return false;">
<input   style=position:absolute;top:80%;left:5%;width:40%; type="text" id="userInput">
<input   style=position:absolute;top:50%;left:5%;width:40%; type="submit"    onclick="name()">
</form>

and this is javascript part:

function name()
{
var input = document.getElementById("userInput");
alert(input);
}

Answer

PiLHA picture PiLHA · Jul 2, 2013

It doesn't work because name is a reserved word in JavaScript. Change the function name to something else.

See http://www.quackit.com/javascript/javascript_reserved_words.cfm

<form id="form" onsubmit="return false;">
    <input style="position:absolute; top:80%; left:5%; width:40%;" type="text" id="userInput" />
    <input style="position:absolute; top:50%; left:5%; width:40%;" type="submit" onclick="othername();" />
</form>

function othername() {
    var input = document.getElementById("userInput").value;
    alert(input);
}