skip to Main Content

I have 3 input fields, I want to update the value of the 3rd one dynamically by adding the value of the 1st and 2nd input field.

1 field -> value ‘5’

2 field -> value ‘3’

3 field which is disabled when I finish typing in the 2nd and 1st field should have value -> ‘8’

this is the one way I tried to do it in Javascript:

document.addEventListener('DOMContentLoaded', function () {
   let time_in_min = document.querySelector('#length_min').value;
   let time_in_sec = document.querySelector('#length_sec').value;

   let total_time_in_secs = (min * 60) + sec;

   document.querySelector('#total_length_sec').value = total_time_in_secs;
});

thi is the html input

<div class="in">
   <input id="total_length_sec" name="total_length_sec" type="number" min="0" disabled="disabled" class="validate" />
   <label for="total_length_sec">Total time in seconds</label>
</div>

but when I reload the page in the 3rd field the value it’s ‘0’ and it remains 0 even if I change the value of the 1st and 2nd field

2

Answers


  1. min and sec not yet declared

    document.addEventListener('DOMContentLoaded', function () {
       let min = document.querySelector('#length_min').value;
       let sec = document.querySelector('#length_sec').value;
    
       let total_time_in_secs = (min * 60) + Number(sec);
    
       document.querySelector('#total_length_sec').value = total_time_in_secs;
    });
    <input id="length_min" value="5"/><br>
    <input id="length_sec" value="3"/><br>
    <input id="total_length_sec"/>
    Login or Signup to reply.
  2. The code that you wrote is runs in the beginning and not every time the value of the inputs fields changes, So what you have to do is to listen to "change" event on the input.

    const input = document.querySelector("input");
    
    input.addEventListener("change", (event)=>{
         console.log(event.target.value);
         // do whatever you want with this value.
    });
    

    This should work for, good luck.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search