如何遍历文本字段并将值推入数组

时间:2020-04-09 13:26:00

标签: javascript

我试图制作一个遍历表单并将其值存储到按键上的数组中的脚本。然后,该数组以连接文本的形式显示为另一种称为“ resultBox”的形式。当我尝试使用document.GetElementById方法进行访问时,它给出了未捕获的TypeError:无法读取null的属性“值”。

var values = [];

function getKeys(){
    for(var i = 0; i<myForm.length; i++){
        console.log(myForm[i].value);
        var txtValue = document.getElementById(myForm).value;
        values.push(txtValue);
        console.log(values);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excercise 2</title>
    <script src ="script.js"></script>
    <style>
        input[type=text] {
                width: 50%;
                padding: 12px 20px;
                margin: 8px 0;
                box-sizing: border-box;
                }
    </style>
</head>
<body>
    <form id="myForm">
        <label for="txt1">Text Box 1</label>
        <input type = "text" onkeyup = 'getKeys()'id='txt1' name="txt1"> <br><br>
        <label for="txt2">Text Box 2</label>
        <input type = "text" id='txt2' name="txt2"><br><br>
        <label for="txt3">Text Box 3</label>
        <input type = "text" id='txt3' name="txt3"><br><br>
        <label for="txt4">Text Box 4</label>
        <input type = "text" id='txt4' name="txt4"><br><br>
        <label for="txt5">Text Box 5</label>
        <input type = "text" id='txt5' name="txt5"><br><br>
        <label for="txt6">Text Box 6</label>
        <input type = "text" id='txt6' name="txt6"><br><br>
    </form>
    <form id ="resultBox">
        <label for="txtResult">Result Box</label>
        <input type = "text" id ="txtResult" name="txtResult" readonly><br><br>
    </form>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

您可以尝试使用一些内置方法,例如querySelectorAll()map()filter()join(),如下所示:

var inputList = document.querySelectorAll('#myForm [type=text]:not(#txt6)');
inputList.forEach(function(input){
  input.addEventListener('input', function(){
    var values = Array.from(inputList).map(el => el.value.trim()).filter(v => v).join(', ');
    document.getElementById('txtResult').value = values;
  });
});
input[type=text] {
  width: 50%;
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
}
<form id="myForm">
  <label for="txt1">Text Box 1</label>
  <input type = "text" id='txt1' name="txt1"> <br><br>
  <label for="txt2">Text Box 2</label>
  <input type = "text" id='txt2' name="txt2"><br><br>
  <label for="txt3">Text Box 3</label>
  <input type = "text" id='txt3' name="txt3"><br><br>
  <label for="txt4">Text Box 4</label>
  <input type = "text" id='txt4' name="txt4"><br><br>
  <label for="txt5">Text Box 5</label>
  <input type = "text" id='txt5' name="txt5"><br><br>
  <label for="txt6">Text Box 6</label>
  <input type = "text" id='txt6' name="txt6"><br><br>
</form>
<form id ="resultBox">
  <label for="txtResult">Result Box</label>
  <input type = "text" id ="txtResult" name="txtResult" readonly> <br><br>
</form>