LaVOZs

The World’s Largest Online Community for Developers

'; javascript - Value gets copied when entered manually, but not automatically on click - LavOzs.Com

Two fields input1 and input2 gives a total sum to input3 on click and it needs to be copied to the next input4 field, but it doesn't.

Although if you enter the value to input3 manually then it gets copied? (it actually doesn't get copied live until you click e.g. tab or click anywhere with the mouse, also don't know how to resolve)

Full code https://jsfiddle.net/tn6wr4xc/1/

So basically when you click the first Sum button it should copy the value to the input4, but it doesn't, only when entered manually.

Sorry for ghetto code, I know it's vanilla and jQuery, real beginner here.

You should use input event to make the immediate changes to output the result.

I will think of the solution in a different approach than yours.

First you can target all the inputs with class formA and formB using querySelectorAll(). Then loop through them to attach the event (input) using forEach() and addEventListener(). Inside the event handler function you can target only specific inputs related to the current element. You can find the sum of them using map() and reduce(). Finally store the sum in the relevant element.

var inputs = document.querySelectorAll('.formA, .formB');

Array.from(inputs).forEach(function(el){
  el.addEventListener('input', function(){
    var group = this.closest('div').querySelectorAll('[class^=form]');
    var sum = Array.from(group).map(i => Number(i.value)).reduce((a,c) => a+c,0);
    this.closest('div').querySelector('[name=total]').value = sum;
  });
});
<form id="forms">
  <div class="form-a">
    <p>Form A</p>
    input1 : <input class="formA form-1" type="text" name="qty1"/><br>
    input2 : <input class="formA form-2" type="text" name="qty2"/><br>
    input3 (total) : <input class="total-1" type="text" name="total" id="total"/>
  </div>
  <hr>

  <div class="form-b">
    <p>Form B</p>
    input4 : <input class="formB form-3" type="text" name="qty3"/><br>
    input5 : <input class="formB form-4" type="text" name="qty4"/><br>
    input6 (total) : <input type="text" name="total" id="total2"/>
  </div>
  <input type="reset" value="Reset">
</form>

I think you can't do it by that way because you update the value property by JavaScript which is not "by a user" so the event is not fired as desired.

But in order to achieve what you wanted, you can look through this link. They describe many ways to overcome the problem. And then one of the most common is to directly modify the input4 value after the you have modify the input3 one by this way ... result.value = sum; $('.form-3').val(sum);