Issue
I have the follow code:
I want to do a plus with all inputs, and I'm new in this process, but i try.
var num1 = document.getElementByID('pree');
var num2 = document.getElementByID('pree1');
var num3 = document.getElementByID('pree2');
var num4 = document.getElementByID('pree3');
var result = document.getElementByID('num1 + num2+ num3+ num4');
<input type="number" name="pree" value="" id="pree" class="form-control">
<input type="number" name="pree1" value="" id="pree1" class="form-control">
<input type="number" name="pree2" value="" id="pree2" class="form-control">
<input type="number" name="pree3" value="" id="pree3" class="form-control">
<input type="number" name="result" value="" id="result" class="result">
I'm really new to this and would like someone to help me with it, thank you very much in advance.
Solution
getElementByID
is a typo. The method isgetElementById
(small "d")Even if you corrected the typo
var result = document.getElementById('num1 + num2+ num3+ num4');
won't do anything because'num1 + num2+ num3+ num4'
is not the id of any element. You want to assign the total of adding thevalues
of those inputs together to thevalue
attribute of your result element.You're not checking for any changes on those inputs for you to be able to create the total. For that you'll need a listener.
Here's a slightly more modern approach. It uses event delegation to attach a listener to a containing element to catch change
events from the inputs as they "bubble up" the DOM. That listener calls the handleChange
function.
The handleChange
function resets the total, iterates over all the inputs, and adds their value to the total. Then the value of the result
is set.
// Cache the elements
const container = document.querySelector('#container');
const inputs = document.querySelectorAll('input[type="number"]');
const result = document.querySelector('#result');
// Add a listener to the container
container.addEventListener('change', handleChange, false);
// Reset the total, iterate over the input elements,
// and add their value to the total, coercing the string
// to a number first. Finally add that total to the
// value of the `result` element
function handleChange() {
let total = 0;
inputs.forEach(input => total += Number(input.value));
result.value = total;
}
<div id="container">
<input type="number" name="pree">
<input type="number" name="pree1">
<input type="number" name="pree2">
<input type="number" name="pree3">
<br />
Result: <input id="result">
</div>
Additional documentation
Answered By - Andy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.