jquery 使用.txt文件填充HTML表单中的许多文本区域

gajydyqb  于 2022-12-26  发布在  jQuery
关注(0)|答案(2)|浏览(173)

当选择txt文件时,我希望添加与文件中行数一样多的输入,并将每行的文本放入生成的输入中。
https://jsfiddle.net/w80dv2fx/

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Untitled Document</title>
</head>

<body>

  <form name="mainForm" method="get" id="Main">
    <p>input 1:<textarea id="input1" cols="20" rows="2"></textarea>
      <p>input 2:<textarea id="input2" cols="20" rows="2"></textarea>
        <p>input 3:<textarea id="input3" cols="20" rows="2"></textarea>
          <p>
            <div>
              <label for="file">Choose file to upload</label>
              <input type="file" id='fileinput' accept=".txt">
            </div>
  </form>


</body>

</html>

杰奎琳:

(function() {
  var input = document.getElementById("fileinput");
  input.addEventListener("change", loadFile, false);

  function loadFile() {
    var file, fr;

    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }

    if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    } else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    } else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
    }

    function receivedText() {
      var data = fr.result.split('\n');
      document.getElementById("input1").value = data[0];
      document.getElementById("input2").value = data[1];
      document.getElementById("input3").value = data[2];
    }
  }
})();

现在它只对3个输入起作用,不会像行数那样添加那么多的输入。

bkhjykvo

bkhjykvo1#

超文本标记语言

<form name="mainForm" method="get" id="Main">
    
          <p>
            <div>
              <label for="file">Choose file to upload</label>
              <input type="file" id='fileinput' accept=".txt">
            </div>
  </form>

javascript接收文本()函数

function receivedText() {
  var data = fr.result.split('\n');
  for(let i = 0; i < data.length; i++) {
    let app = document.querySelector('#Main');
    let html = `<p>input ${i}:<textarea id="input1" cols="20" rows="2">${data[i]}</textarea></p>`;
    app.insertAdjacentHTML("beforebegin", html);
  }
}
qvtsj1bj

qvtsj1bj2#

如我所见,u只处理前3行(数据[0]、数据[1]、数据[2])。
您需要创建与线数量相同的输入
因此在receivedText函数中,需要运行data变量

var data = fr.result.split('\n');

const formEl = document.querySelector('form[name=mainForm]')
// or define id attribute for parent element
data.forEach((line) => {|
  const inputEl = document.createElement('input')
  input.value = line
  formEl.appendChild(input)
})

相关问题