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

8

23

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);
}
Harwin answered 2/7, 2013 at 18:53 Comment(1)
Just change your function's name to something else such as username because in JavaScript, name is a reserved word.Nonperformance
S
33

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);
}
Swelling answered 2/7, 2013 at 19:7 Comment(0)
T
8

First, make your markup more portable/reusable. I also set the button's type to 'button' instead of using the onsubmit attribute. You can toggle the type attribute to submit if the form needs to interact with a server.

<div class='wrapper'>
<form id='nameForm'>
<div class='form-uname'>
    <label id='nameLable' for='nameField'>Create a username:</label>
    <input id='nameField' type='text' maxlength='25'></input>
</div>
<div class='form-sub'>
    <button id='subButton' type='button'>Print your name!</button>
</div>
</form>

<div>
    <p id='result'></p></div>
</div>

Next write a general function for retrieving the username into a variable. It checks to make sure the variable holding the username has it least three characters in it. You can change this to whatever constant you want.

function getUserName() {
var nameField = document.getElementById('nameField').value;
var result = document.getElementById('result');

if (nameField.length < 3) {
    result.textContent = 'Username must contain at least 3 characters';
    //alert('Username must contain at least 3 characters');
} else {
    result.textContent = 'Your username is: ' + nameField;
    //alert(nameField);
}
}

Next, I created an event listener for the button. It's generally considered the bad practice to have inline js calls.

var subButton = document.getElementById('subButton');
subButton.addEventListener('click', getUserName, false); 

Here is a working and lightly styled demo:

CodePen demo of this answer.

Templin answered 7/9, 2015 at 22:41 Comment(0)
G
4

Change your javascript to:

var input = document.getElementById('userInput').value;

This will get the value that has been types into the text box, not a DOM object

Garlic answered 2/7, 2013 at 18:55 Comment(2)
i have tried this and it doesnt seem to work. from what ive read, it should but..Harwin
i have fixed this! it seems so obvious now. it turns out that the function wont work with the function name as "name()" after changing to "username()" it works perfectly!Harwin
C
2

You can use PHP and JavaScript Together:

<input type="hidden" id="CatId" value="<?php echo $categoryId; ?>">

Now Update the JavaScript:

var categoryId = document.getElementById('CatId').value;
Cordiecordier answered 4/1, 2019 at 10:32 Comment(0)
T
2

I found this to work best for me try this fiddle

document.getElementById("btnmyNumber").addEventListener("click", myFunctionVar);
function myFunctionVar() {
  var numberr = parseInt(document.getElementById("myNumber").value, 10);
  // alert(numberr);
  if ( numberr > 1) {

    document.getElementById("minusE5").style.display = "none";



}}
   <form onsubmit="return false;">
       <input class="button button3" type="number" id="myNumber" value="" min="0" max="30">
       <input type="submit" id="btnmyNumber">

       </form>
Three answered 22/5, 2019 at 19:47 Comment(0)
I
1
<html>    
    <input type="text" placeholder ="username" id="userinput">
    <br>
    <input type="password" placeholder="password">
    <br>
    <button type="submit" onclick="myfunc()" id="demo">click me</button>

    <script type="text/javascript">
        function myfunc() {
            var input = document.getElementById('userinput');
            alert(input.value);
        } 
    </script>
</html>

Illustrative answered 30/11, 2019 at 10:1 Comment(1)
Welcome to SO! You could improve your answer by providing a short description of the code. See help section (stackoverflow.com/help) for further guidance.Irreligious
M
1

I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.

var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
Movable answered 23/12, 2020 at 10:25 Comment(0)
T
0

<!DOCTYPE html>
<html>
<body>

<p><input type="text" placeholder ="username" id="userinput">
    <button id="demo">click me</button></p>

    <script>
        document.getElementById("demo").onclick = function(){
        var user = document.getElementById("userinput").value;
         alert(user);

       }
    </script>

</body>
</html> 

click me

<script>
    document.getElementById("demo").onclick = function(){
    var user = document.getElementById("userinput").value;
     alert(user);

   }
</script>
Tonguelashing answered 16/11, 2022 at 17:56 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Footton

© 2022 - 2024 — McMap. All rights reserved.