4个百分比输入框,如何将数值最大调整到100%

时间:2019-02-19 15:31:11

标签: javascript angularjs

我想向用户显示四个输入框,每个输入框的25%开始。如果用户更改了输入框中的任何值,则将在其他三个框中显示的值进行相应计算。例如:假设用户选择将主题之一更改为20%,我希望其他主题为26.6

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以先获取所有元素,然后在focus上添加一个类,然后在blur上将其删除。此类将用于定位其余元素并更新其值

//get all the input with specified name and add event lister to it
[...document.getElementsByName('userInp')].forEach(function(item) {
  // on focusing adding a class to the current target
  item.addEventListener("focus", function(e) {
    e.target.classList.add('focus')

  });
  // removing the class on blurring from current target
  item.addEventListener("blur", function(e) {
    e.target.classList.remove('focus')

  });
  item.addEventListener('keyup', function(e) {
    // get the value from the target input
    let getVal = e.target.value;
    if (getVal < 100) {
      // devide equally among rest of the inputs for this example it is 3
      let eachVal = (100 - getVal) / 3
      // then select all the input which does not have class focus
      // and update their value
      document.querySelectorAll("input:not(.focus)").forEach(function(elem) {
        elem.value = eachVal.toFixed(2)
      })

    }


  })
})
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>
<input type='text' name='userInp' value='25'>