在不使用 jQuery 的情况下获取 JavaScript 中的输入值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21782243/
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
Get input value in JavaScript without using jQuery?
提问by kyr
Let's say I have an input field like this:
假设我有一个这样的输入字段:
<input type="text" id="input" value="This is my value">
How can I get the attribute value? In jQuery, I can easily get it with:
如何获取属性值?在 jQuery 中,我可以很容易地得到它:
$('#input').val() //-> This is my value
How do I do so using pure JavaScript?
我如何使用纯 JavaScript 做到这一点?
回答by AfromanJ
You can get the value by targeting the ID.
Where inputID
is the IDof your input or textarea:
您可以通过定位 ID 来获取值。您的输入或文本区域的ID
在哪里:inputID
document.getElementById('inputID').value;
You can also do it by targeting the name attribute.
Where inputID
is the Nameof your input or textarea:
您也可以通过定位 name 属性来实现。您的输入或文本区域的名称
在哪里:inputID
document.getElementsByName('inputID')[0].value;
回答by Mark
The element must have an ID
该元素必须有一个 ID
<input type="text" id="text-field-id" value="A test!">
And then you do this:
然后你这样做:
var value = document.getElementById('text-field-id').value;
回答by Pranav C Balan
You can use getElementById()
, to get value use value
property
您可以使用getElementById()
, 来获取价值使用value
属性
<input type-"text" id="text" />
var text=document.getElementById('text').value;
回答by Eswara Reddy
Try this
试试这个
document.getElementById("input-id").value
回答by Dieterg
Yes you are right, everything that is written in jQuery can be written in pure Javascript
是的,您是对的,用 jQuery 编写的所有内容都可以用纯 Javascript 编写
var value = document.querySelector('#yourInput').value;
回答by Theox
You can use this :
你可以使用这个:
<input type="hidden" id="yourID" name="msg" value="" style="display:none"/>
var Msg="abc";
document.getElementById('yourID').value = Msg;