![](/img/trans.png)
[英]Dynamically changing a value in a function with Javascript using input text fields
[英]Using Javascript to identify and input text to input fields
我希望能夠識別所有輸入字段,以便我可以存儲它們並運行 for 循環,該循環將從數組中將文本輸入到輸入字段中並提交表單以進行響應。
var inputs = document.forms["form_name"].getElementsByTagName("input");
var text = ["brown", "white", "blue", "green"]
for (var i = 0; i < inputs.length; i++) {
for (word of text){
document.getElementById(inputs[i]).textContent(word)
}
}
不需要循環文本也不需要document.getElementById
因為已經獲取更改值的元素使用值而不是 textContent
var inputs = document.forms["myForm"].getElementsByTagName("input"); var text = ["brown", "white", "blue", "green"] for (var i = 0; i < inputs.length; i++) { inputs[i].value = text[i]; }
<form name="myForm" > f Name: <input type="text" name="fname"> m Name: <input type="text" name="mname"> l Name: <input type="text" name="lname"> dob: <input type="text" name="dob"> </form> <button>Go to Next</button>
不要使用getElementsByTagName()
或document.forms
。 這些是有缺點的舊 API。
相反,使用.querySelectorAll()
並利用以下事實:您可以使用Array.forEach()
方法循環.querySelectorAll()
的結果,如下所示:
var values = ["brown", "white", "blue", "green"]; // Loop over all the inputs document.querySelectorAll("input").forEach(function(input, index){ // Set the current input with the corresponding item from the values array input.value = values[index]; }); // Submit the form document.querySelector("form").submit();
<form action="https://www.example.com" method="post"> <div>Input 1 <input name="item1"></div> <div>Input 2 <input name="item2"></div> <div>Input 3 <input name="item3"></div> <div>Input 4 <input name="item4"></div> </form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.