[英]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.