如何将用户输入的表单值从 html 传递到 javascript?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22116017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass a user entered form value from html to javascript?
提问by
It is possible to pass a value from javascript to html by writing it to a tag. However, if I would wish to pass a user defined value (etc, entered by the person viewing the webpage) to java script so I can do things with it, what would be the most easiest way possible?
通过将值写入标签,可以将值从 javascript 传递到 html。但是,如果我希望将用户定义的值(等,由查看网页的人输入)传递给 java 脚本,以便我可以用它做事,最简单的方法是什么?
At the moment, I have something like this:
目前,我有这样的事情:
<div class="entry foreground-color">
<form>
<input type="text" name="commands" size="60"/>
</form>
</div>
How can I make the value from the form be passed to my javascript?
如何将表单中的值传递给我的 javascript?
Or, am I going in a totally wrong direction? If so, what would be the correct way to get user input, and pass it on to javascript?
或者,我是否正朝着完全错误的方向前进?如果是这样,获取用户输入并将其传递给 javascript 的正确方法是什么?
EDIT: Apologies for my misuse of terminology. I am making a text based adventure game, and I want the user to be able to type in a response, press enter, and have the response be sent to javascript, so I can use javascript to evaluate the response (etc "go south", "go north"), and write back to the element with the new situation (etc "as you went south, you found a troll").
编辑:为我滥用术语道歉。我正在制作一个基于文本的冒险游戏,我希望用户能够输入响应,按 Enter,然后将响应发送到 javascript,这样我就可以使用 javascript 来评估响应(等“向南” ,“向北”),并用新情况写回元素(例如“当你向南时,你发现了一个巨魔”)。
采纳答案by Anonymous
You can just stop the form from submitting and get the value:
您可以停止表单提交并获取值:
HTML:
HTML:
<div class="entry foreground-color">
<form onsubmit="return getValue('commands')">
<input type="text" name="commands" size="60" id="commands"/>
</form>
</div>
JavaScript:
JavaScript:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
Fiddle: Fiddle
小提琴:Fiddle
If you want to clear the box afterwards, use:
如果您想在之后清除该框,请使用:
document.getElementById(id).value = '';
Like so:
像这样:
function getValue (id) {
text = document.getElementById(id).value; //value of the text input
alert(text);
document.getElementById(id).value = '';
return false;
}
回答by Bohdan Ganicky
The input value is already available for Javascript via DOM API:
输入值已经可以通过 DOM API 用于 Javascript:
document.getElementsByName( "commands" )[0].value
回答by Saro Ta?ciyan
You can get the valueof your input control using:
您可以使用以下方法获取输入控件的值:
document.getElementsByName("commands")[0].value;
document.getElementsByName("commands")[0].value;
Since getElementsByName()
method returns an Array
of elements with specified name, you will need to take the firstelement assuming that there is only oneelements with name
attribute commands
.
由于getElementsByName()
方法返回Array
具有指定名称的元素,假设只有一个具有属性的元素,您将需要取第一个元素。name
commands
Instead of that, for simplicity and uniqueness, i suggest you use the famous way to achieve that using id
attribute and getElementById()
method.
取而代之的是,为了简单和独特,我建议您使用著名的方法来使用id
属性和getElementById()
方法来实现这一点。
回答by Paul Rad
To get the value of an HTML element, first, you need to get the desired element (you can use theses methods):
要获取 HTML 元素的值,首先需要获取所需的元素(可以使用这些方法):
- getElementById
- getElementsByTagName
- getElementsByClassName
- querySelector (moderns browsers)
- querySelectorAll (moderns browsers)
- getElementById
- getElementsByTagName
- getElementsByClassName
- querySelector(现代浏览器)
- querySelectorAll(现代浏览器)
Theses methods depending on document
(documentation).
这些方法取决于document
(文档)。
So in your case you can try something like this:
所以在你的情况下,你可以尝试这样的事情:
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
But you need to set a "catcher" on the form default action. So:
但是您需要在表单默认操作上设置一个“捕手”。所以:
<form>
Become:
变得:
<form onsubmit="return getValue()">
And you set the javascript code above in the getValue function:
然后在 getValue 函数中设置上面的 javascript 代码:
function getValue() {
var inputs = document.getElementsByTagName('input'),
commandValue = null;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name === "commands") {
commandValue = inputs[i].value; // get the element value
}
}
alert (commandValue); // show the value
return false; // prevent default form action
};
回答by Vinay Pratap Singh
<input type="text" name="commands" size="60" id="commands"/>
var input = document.getElementById("commands").value;
or
或者
document.getElementsByName( "commands" )[0].value
now do anything with this
现在做任何事情
回答by Diego
You are in the right path :)
你走在正确的道路上:)
For example you can do something like this (see http://jsfiddle.net/ahLch/):
例如,您可以执行以下操作(请参阅http://jsfiddle.net/ahLch/):
HTML:
HTML:
<h1 id="commandsExample"></h1>
<div class="entry foreground-color">
<form>
<input type="text" id="commands" size="60"/>
</form>
</div>
JavaScript:
JavaScript:
var input = document.getElementById('commands');
var example = document.getElementById('commandsExample');
input.addEventListener('change', function () {
example.innerHTML= input.value;
});
A couple of things to note:
需要注意的几点:
If you are new to JavaScript, and you wish to make your code cross browser (especially if you want to target old versions of IE), take a look to jQuery.
If you wish to learn how to use plain DOM APIs provided by the browser without the jQuery layer, take a look to: http://youmightnotneedjquery.com/(it's very useful once that you learned jQuery basics).
There are a couple of ways to get the value:
Intercepting from submmit event: I don't recommend it, you have to take care of avoiding the default submit behavior, and you have to create a form around your input field. That was necessary in old browsers, but today is not.
changeevent: it's fired when the input value has changed and the input looses the focus (is the usual event used for form validation).
keydownand keyup: they give you more control, by capturing each keystroke, but it's lower level than the change event. For a complete reference see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
Use "id" instead of "name". Name is only necessary when you want to submit the value, in new browsers you can leave just input tag without a form.
如果您不熟悉 JavaScript,并且希望使您的代码跨浏览器(特别是如果您希望针对旧版本的 IE),请查看 jQuery。
如果您想学习如何在没有 jQuery 层的情况下使用浏览器提供的普通 DOM API,请查看:http: //youmightnotneedjquery.com/(一旦您学习了 jQuery 基础知识,这将非常有用)。
有两种获取值的方法:
从提交事件拦截:我不推荐它,您必须注意避免默认提交行为,并且您必须在输入字段周围创建一个表单。这在旧浏览器中是必要的,但今天不是。
change事件:当输入值发生变化并且输入失去焦点时会触发它(通常用于表单验证的事件)。
keydown和keyup:它们通过捕获每个击键为您提供更多控制,但它比更改事件级别低。有关完整参考,请参阅:https: //developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
使用“id”而不是“name”。名称仅在您要提交值时才需要,在新浏览器中,您可以只留下输入标签而无需表单。
回答by Niels
Getting the value of the input tag is quite easy with jQuery. (I take it you need this anyway to actually send the message via AJAX to a server..?)
使用 jQuery 获取 input 标签的值非常容易。(我认为无论如何你都需要这个才能通过 AJAX 将消息实际发送到服务器..?)
$("#idofinput").val(); will copy the value, $("#idofinput").val(''); will empty it.
$("#idofinput").val(); 将复制值,$("#idofinput").val(''); 将它清空。
You probably want to do this without actually submitting a form. Recreating one in javascript isn't to hard. For the submit on enter you can use something like this:
您可能希望在不实际提交表单的情况下执行此操作。在 javascript 中重新创建一个并不难。对于输入时提交,您可以使用以下内容:
function checkEnter(e)
{
var keynum;
if(window.event) // IE8 and earlier
{
keynum = e.keyCode;
}
else if(e.which) // IE9/Firefox/Chrome/Opera/Safari
{
keynum = e.which;
}
if(keynum==13)
{
sendMessage();
}
}