首页 > 解决方案 > 如何使用 Javascript 将数组从 textarea 移动到表格

问题描述

我正在尝试将输入结果从 textarea 移动到表格中。我正在使用 javascript 来获取数组值。

但我现在能做的只是在一个文本区域中显示它。我很困惑如何将数组值分隔到表中。

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
<input type="button" value="next" onclick="next3();">

<textarea id="koord" value="" style="width:220px;"></textarea>

<script>
function next3(){

    var vx = String($("input[name='px[]']").map(function(){return $(this).val();}).get());  
    var vy = String($("input[name='py[]']").map(function(){return $(this).val();}).get());

    var vxArr = vx.split(",");
    var vyArr = vy.split(",");

    var lenArr = vxArr.length;

    var isi = "";
    for (i = 0; i < lenArr; i++) {
        var koord = "X" + vxArr[i] + " " + "Y" + vyArr[i];
        //alert (koord);
        var isi = isi + ', ' + koord;

    } 

    //alert (isi);

    var lastChar = isi.substr(2); // => "1"

    $("#koord").val(lastChar);

}
</script>

textarea 中的结果是

图片链接https://postimg.cc/fJWHhxp9

我所期望的是

+---------+---------+
| X Point | Y Point |
+---------+---------+
|     123 |     456 |
|     123 |     456 |
|     123 |     456 |
|     123 |     456 |
+---------+---------+

标签: javascriptjqueryhtml

解决方案


您有固定长度的输入,您可以轻松地将数组用作值并从中生成表,而不是字符串,您可以将其保留为数组并附加行。

function next3() {

  var vx = ($("input[name='px[]']").map(function() {
    return $(this).val();
  }).get());
  var vy = ($("input[name='py[]']").map(function() {
    return $(this).val();
  }).get());
  
  $('table tbody').html('');
  
  vx.forEach((a, index) => {
    if (a !== '' && vy[index] !== '') {
      $('table tbody').append('<tr><td>' + a + '</td><td>' + vy[index] + '</td></tr>')
    }
  })

}
table {
  border: 1px solid black
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text"
  name="py[]" value="" /><br> x <input type="text" name="px[]" value="" /> y <input type="text" name="py[]" value="" /><br>
<input type="button" value="next" onclick="next3();">

<textarea id="koord" value="" style="width:220px;"></textarea>
<table>
  <thead></thead>
  <tbody></tbody>
</table>


推荐阅读