Issue
I want to show the user four input boxes, starting with 25% each of them. If the user changes any of the values in a input box the value displayed in the three others will calculate accordingly. Example :let's say that a user choose to change one of theme to 20% I expect the others to be 26.6
Solution
You can first get all the elements then add a class on focus
remove it on blur
. This class will be used to target rest of the element and update their value
//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'>
Answered By - brk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.