Vanilla JS Instant Update

Hello everybody :slight_smile:

OK, I have say three text boxes. Now what I want is that as soon as I type in first and second text box … their sum result should automatically be shown in third textbox.

Can this be done in Vanilla JS?

Please just gimme a little explanation :slight_smile:
Thank you.

Edit: My gut feeling is telling me that it can’t be done but even if it can be done then I must use Ajax. So you see… I am not sure. Google didn’t helped much.

There’s probably a more elegant solution, but this works…


<input type="text" id="field1" name="field1" value="" />
<input type="text" id="field2" name="field2" value="" />
<input type="text" id="field3" name="field3" value="" />


document.getElementById("field1").onchange = function() {
document.getElementById("field2").onchange = function() {

function addValues() {
    var field1 = document.getElementById("field1");
    var field2 = document.getElementById("field2");

    // added a numeric check just to prevent niggly results....
    if (isNumeric(field1.value) && isNumeric(field2.value)) {
      	  document.getElementById("field3").value = (parseFloat(field1.value) + parseFloat(field2.value)).toString();

function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
1 Like

With jQuery:

<div id="inputs">
  <input type="number" />
  <input type="number" />
  <input type="text" value="0"/>

$("#inputs").on("keyup", function(){
  let val1 = $("#inputs input:nth-child(1)").val();
  let val2 = $("#inputs input:nth-child(2)").val();
  $("input[type='text']").val(val1 * val2);


Edit: Oops. Just saw the OP wants vanilla JS.

1 Like

Is that new math? Last time I checked, that wasn’t a sum :wink:

err, might be :shifty:

Not really on my game today.


FWIW, here’s the VanillaJS version… requires only one single DOM query though. B-)

  .addEventListener('keyup', function() {
    const val1 = this.children[0].value
    const val2 = this.children[1].value
    this.children[2].value = val1 + val2

Sorry for late response but Thank you to everybody for the help. That’s what I needed :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.