如何在JavaScript中设置一个表单<input>文本字段的默认值?
当前回答
2023的答案
您现在可以使用document.querySelector()来代替使用document.getElementById()来处理不同的情况
更多信息从另一个堆栈溢出回答:
querySelector允许您找到具有不能被规则的元素 用getElementById和getElementsByClassName表示
例子:
document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
or
let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';
测试:
document.querySelector(“输入[name = " myInput]”)。value = '任何你想要的!'; <input type="text" name="myInput" id="myInput" placeholder="Your text">
其他回答
这是简单的;一个例子是:
<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>
document.getElementById("fieldId").value = "Value";
or
document.forms['formId']['fieldId'].value = "Value";
or
document.getElementById("fieldId").setAttribute('value','Value');
这是一种方法:
document.getElementById("nameofid").value = "My value";
如果字段出于某种原因只有name属性,没有其他属性,你可以尝试这样做:
document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";
如果您的表单包含一个输入字段
<input type='text' id='id1' />
然后你可以用javascript编写如下所示的代码来设置它的值为
document.getElementById('id1').value='text to be displayed' ;
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- 创建圈div比使用图像更容易的方法?