Javascript 设置输入字段的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7609130/
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
Set the value of an input field
提问by SebastianOpperman
How would you set the default value of a form <input>
text field in JavaScript?
你将如何<input>
在 JavaScript 中设置表单文本字段的默认值?
回答by James
This is one way of doing it:
这是一种方法:
document.getElementById("mytext").value = "My value";
回答by Varada
if your form contains an input field like
如果您的表单包含一个输入字段,如
<input type='text' id='id1' />
then you can write the code in javascript as given below to set its value as
那么你可以用下面给出的javascript编写代码来将它的值设置为
document.getElementById('id1').value='text to be displayed' ;
回答by Pepe Amoedo
I use 'setAttribute' function:
我使用“setAttribute”函数:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
document.getElementById("example").setAttribute('value','My default value');
</script>
回答by dallinchase
Try out these.
试试这些。
document.getElementById("current").value = 12
// or
var current = document.getElementById("current");
current.value = 12
回答by php-coder
The answer is really simple
答案其实很简单
// Your HTML text field
<input type="text" name="name" id="txt">
//Your javascript
<script type="text/javascript">
document.getElementById("txt").value = "My default value";
</script>
Or if you want to avoid JavaScript entirely: You can define it just using HTML
或者,如果您想完全避免使用 JavaScript:您可以仅使用 HTML 来定义它
<input type="text" name="name" id="txt" value="My default value">
回答by David Caissy
If you are using multiple forms, you can use:
如果您使用多个表格,您可以使用:
<form name='myForm'>
<input type='text' name='name' value=''>
</form>
<script type="text/javascript">
document.forms['myForm']['name'].value = "New value";
</script>
回答by RWolfe
The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute
简单的答案不是在 Javascript 中获取占位符的最简单方法是通过 placeholder 属性
<input type="text" name="text_box_1" placeholder="My Default Value" />
回答by ultimatetechie
It's simple; An example is:
这很简单; 一个例子是:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>
回答by Arun Karnawat
document.getElementById("fieldId").value = "Value";
or
或者
document.forms['formId']['fieldId'].value = "Value";
or
或者
document.getElementById("fieldId").setAttribute('value','Value');
回答by Amranur Rahman
This part you use in html
你在html中使用的这部分
<input id="latitude" type="text" name="latitude"></p>
This is javaScript:
这是javaScript:
<script>
document.getElementById("latitude").value=25;
</script>