自动填写表格

时间:2019-07-08 19:31:15

标签: javascript automation

我正在寻找一种自动化表格的方法。
详细信息如下:

  1. 提取特定数字(显示在其html中)
  2. 对提取的数字(该数字的百分比)进行一些计算
  3. 然后自动使用结果填充剩余的输入字段,而不用键入它。

1 个答案:

答案 0 :(得分:0)

这是常见的形式。解决方案取决于您使用的框架/库。假设您没有使用,请按照以下步骤操作:

https://jsfiddle.net/f52h1smj/1/

粗糙的HTML:

<form>
  <label for="number">Number: </label>
  <input id="number" type="number" />
  <br /> <br />
  <label for="calculatedNumber">Calculated Number (50%): </label>
  <input id="calculatedNumber" type="number" disabled="true" />
</form>

JS:

(() => {
  //get the form element nodes 
  const $number = document.getElementById("number");
  const $calculatedNumber = document.getElementById("calculatedNumber");

  //add an event listen to the value you're going to use to pre calculate the other fields
  $number.addEventListener("keyup", (e) => {
    //it's value is available like so
    const value = e.target.value;
    //do some validation so that you're calculations don't throw exceptions
    if (Number(value) !== 0 && !Number.isNaN(value)) {
      //set the value of the other inputs to whatever you like by setting the 'value' property of the node. 
      $calculatedNumber.value = value / 2;
    } else {
      $calculatedNumber.value = null;
    }
  });
})();

在React和Angular之类的框架中,这些事情变得简单得多。