Search code examples
javascripthtmluser-input

How to save user input into a variable in HTML and JavaScript


I am making a game and at the start it asks for your name, I want this name to be saved as variable.

Here is my 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 here is my JavaScript Code

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

Solution

  • 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);
    }