0

I currently have a set of fields and radio buttons that take in some user input. Here is an example:

<div id="age">
        <input type="number" name="age1" value=60>
</div>

I am displaying all the inputted values and want the display to change when the user modifies the input. This is my attempt:

    var inputElements = document.querySelectorAll('input');
    for(var i = 0, len = inputElements.length ; i < len ; i++) {
        inputElements[i].addEventListener('input', updateDisplay());
    }

     function updateDisplay () {
            console.log("test");
            var age = document.querySelector('input[name="age1"]').value;
            document.getElementById("ageComparison").innerHTML = age;
     }

I know that the program enters the method since the "test" message is printed to the console; however, I don't see any change in display according to changes in input. Would appreciate any help.

2 Answers 2

2

While creating the eventlistener, you're just calling updateDisplay. Remove the (). Also, you did not put '#ageComparison' element in your code.

html:

<div id="age">
  <input type="number" name="age1" value=60>
</div>
<div id="ageComparison">
</div>

js:

var inputElements = document.querySelectorAll('input');
for (var i = 0; i < inputElements.length; i++) {
  inputElements[i].addEventListener('input', updateDisplay);
}

function updateDisplay() {
  console.log("test");
  var age = document.querySelector('input[name=age1]').value;
  document.getElementById("ageComparison").innerHTML = age;
}

Example: https://jsfiddle.net/m6r871t6/

Sign up to request clarification or add additional context in comments.

Comments

1

Try avoiding the inner double quotes

   var age = document.querySelector('input[name=age1]').value;

try using

  inputElements[i].addEventListener('change', updateDisplay())

6 Comments

Thanks for your help scaisEdge. I am unable to see the effect of this. What do removing the double quotes do?
Yes and none of the output seemed to have changed.
if the test appear on console .. then the problem is in the selector or in the assignement .. (inside the selector string the inner quote are not needed )
Test does not appear on the console either, when the age input is changed.
then the problem is the listerner try using change .. answer updated .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.