Как такое можно сделать?
Например так...
const oa = document.querySelectorAll('#box input')
oa.forEach(o => o.addEventListener('input', _ => {
const val = [...oa].reduce((s, o, i) => {
const v = +o.value
if (i < 2) s += v
else s -= v
return s
}, 0)
document.querySelector('#price_4').value = val
}))
input {
width: 50px;
}
<span id='box'>
<input type="text" id="price_0" value="" placeholder="price_0"> +
<input type="text" id="price_1" value="" placeholder="price_1"> -
<input type="text" id="price_2" value="" placeholder="price_2"> -
<input type="text" id="price_3" value="" placeholder="price_3"> =
</span>
<input type="text" id="price_4" value="" placeholder="price_4">
По просьбе ТСа привожу еще один пример, который зависит от +
и -
, стоящих перед инпутами
const oa = document.querySelectorAll('#box input')
oa.forEach(o => o.addEventListener('input', _ => {
const val = [...oa].reduce((s, o) => {
const v = +o.value
const act = o.previousSibling.wholeText
if (/\-/.test(act)) s -= v
else s += v
return s
}, 0)
document.querySelector('#price_4').value = val
}))
input {
width: 50px;
}
<span id='box'>
- <input type="text" id="price_0" value="" placeholder="price_0"> +
<input type="text" id="price_1" value="" placeholder="price_1"> +
<input type="text" id="price_2" value="" placeholder="price_2"> -
<input type="text" id="price_3" value="" placeholder="price_3"> =
</span>
<input type="text" id="price_4" value="" placeholder="price_4">