计算输入字段的总数并显示每个输入字段的百分比

时间:2019-01-31 21:37:41

标签: javascript html

我总共有3个输入字段。每个输入字段中都有一个数字。我想获取这3个输入字段的总数,并获取每个输入字段的百分比。

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>pappa's programma</title>
</head>
<body>
    <form>
        <p><br /><br /></p>
        <input type="number" id="a" value="10"><p>10%</p>
        <input type="number" id="b" value="50"><p>50%</p>
        <input type="number" id="c" value="40"><p>40%</p>
        <p id="total">totaal= 100</p>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

总值,然后遍历并将每个值除以总计

html

<div id="app">
  <div class="container">
    <input class="input" value="10" />
    <p class="info"></p>
  </div>
  <div class="container">
    <input class="input" value="20" />
    <p class="info"></p>
  </div>
  <div class="container">
    <input class="input" value="30" />
    <p class="info"></p>
  </div>
</div>

js

const containers = Array.from(document.querySelectorAll('.container'));
const total = containers.reduce((acc, container) => {
  const input = container.querySelector('.input');
  return acc + parseInt(input.value, 10);
}, 0);

containers.forEach(container => {
  const input = container.querySelector('.input');
  const info = container.querySelector('.info');
  info.innerHTML = `${Math.ceil(100 * parseInt(input.value, 10) / total)}%`;
});

答案 1 :(得分:0)

const handleChange = e => {
  const inputs = Array.from(document.querySelectorAll('input'));
  const values = inputs.map(input => +input.value);
  const sum = values.reduce((acc, curr) => acc + curr);
  const percents = values.map(value => 100 * value / sum);

  // Update all percentages
  inputs.forEach((input, index) =>
    input.nextSibling.textContent = `${percents[index].toFixed(2)} %`);

  // Update total value
  document.querySelector('#total').textContent = `total = ${sum}`;
};

// Bind 'change' event to all input fields
Array.from(document.querySelectorAll('input'))
  .forEach(input => input.addEventListener('change', handleChange));
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>pappa's programma</title>
</head>
<body>
    <form>
        <p><br /><br /></p>
        <input type="number" id="a" value="10"><p>10%</p>
        <input type="number" id="b" value="50"><p>50%</p>
        <input type="number" id="c" value="40"><p>40%</p>
        <p id="total">totaal= 100</p>
    </form>
</body>
</html>