4-процентные поля ввода, как динамически регулировать значения до 100% - PullRequest
0 голосов
/ 19 февраля 2019

Я хочу показать пользователю четыре поля ввода, начиная с 25% каждого из них.Если пользователь изменяет любое из значений в поле ввода, значение, отображаемое в трех других, будет рассчитываться соответствующим образом.Пример: предположим, что пользователь решил изменить одну из тем на 20%, я ожидаю, что остальные будут 26,6

enter image description here

1 Ответ

0 голосов
/ 19 февраля 2019

Вы можете сначала получить все элементы, затем добавить класс на 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'>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...