简体   繁体   English

如何将用户输入保存到 HTML 和 JavaScript 中的变量中

[英]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:这是我的 HTML 代码:

<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这是我的 JavaScript 代码

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

It doesn't work because name is a reserved word in JavaScript.它不起作用,因为name是 JavaScript 中的保留字。 Change the function name to something else.将函数名称更改为其他名称。

Seehttp://www.quackit.com/javascript/javascript_reserved_words.cfmhttp://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);
}

First, make your markup more portable/reusable.首先,让你的标记更便携/可重用。 I also set the button's type to 'button' instead of using the onsubmit attribute.我还将按钮的类型设置为'button'而不是使用onsubmit属性。 You can toggle the type attribute to submit if the form needs to interact with a server.如果表单需要与服务器交互,您可以切换type属性以submit

<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.内联 js 调用通常被认为是不好的做法。

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

Here is a working and lightly styled demo:这是一个有效且风格简洁的演示:

CodePen demo of this answer.这个答案的 CodePen 演示。

Change your javascript to:将您的 javascript 更改为:

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

This will get the value that has been types into the text box, not a DOM object这将获取已输入文本框中的值,而不是 DOM 对象

You can use PHP and JavaScript Together:您可以同时使用 PHP 和 JavaScript:

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

Now Update the JavaScript:现在更新 JavaScript:

var categoryId = document.getElementById('CatId').value;

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>

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

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.我的意思是,如果 HTML 方面不需要该变量,则提示脚本将起作用,即使在某些情况下,也可以使用函数。

 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 }

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM