![](/img/trans.png)
[英]How do I check to see if a field has a value before executing document.getElementById?
[英]How do I set the value of a text input field when the field does not have an id but it has a name. I can't use document.getElementById
我试图设置一个输入字段的值,但我无法为其分配ID,因此无法使用document.getElementById。 还有什么其他方法可以为该具有名称的文本输入字段分配值?
您可以使用基本的queryselector选择属性,然后将属性名称放在方括号[
和]
之间。 通过使用等号,属性也可以具有可选值。
这是一个工作示例:
document.querySelector('[name=hello]').value = 'Hello World'
<form> <input type="text" name="hello"> </form>
使用document.getElementsByName
: https : //developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementsByName
const el = document.getElementsByName('name')[0];
el.value = 'someValue';
您可以使用Document.getElementsByname() 。
此方法返回一个元素数组,因此您可能要访问该数组中的第一个元素。
现场示例:
var myInput = document.getElementsByName("my-input")[0]; myInput.value = "Some Text";
<input type="text" name="my-input">
例如,如果输入字段名为“ x”,其格式为名称为“ f”,则:
document.fxvalue = 'some value';
function test() { document.fxvalue = 'It works!'; }
<html> <body> <form name="f"> <input name="x" size="20"> <br> <input type="button" value="Test" onclick="test();"> </form> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.