I created JavaScript that calculate total amount based on two input variables (price, quantity) . The script should take input values from HTML form and show the result in the “Total” field , in the same form. The calculations should be updated on onChange event. How to accomplish this tasks: to pass values of form input fields (Price , Quantity) to Javascript on onChange event and dynamically update “Total” field value in real-time? (without external JS libs)
I looked on some w3s examples how to use the HTML DOM to assign an “onchange” event to an input element.
In HTML part it should be <input type="text" id="fname" onchange="myFunction()">
and in Javascript part:
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
Or also to use the addEventListener() method to attach a “change” event to an input element. But I don’t know what will be better method for this particular case and how to adjust it properly.
Looking at the possible uses of addEventListener method, I see that it’s mainly intended for events such as “mouseover”, “click”, “mouseout”,“mousemove”. This HTML page intended for use mainly on smartphone screen, so these events probably won’t be the most convenient.
I think you should use .value instead of .innerHTML for certain inputs. innerHTML is more useful for handling nested elements and with that code, you just want to change the value of the total field.
I agree with @faust.levity about using .value to pick up either the default or user-entered values of the price and quantity elements. But I think for your purposes you might be happier using the input event for your listener. And, assuming you want to calculate total based on a change to either price or quantity, you will need two listeners, one for each.
But…your code has errors: the HTML structure is not well-formed; there are invalid label/input associations and non-unique id attribute values…
element.addEventListener("input", calculate);
function calculate() {
var inputOne = document.getElementById("price").value;
var inputOne = document.getElementById("quantity").value;
var result = +inputOne + +inputTwo
return result
}
calculate()
not clear how to show result, in the new form? can someone show how it should be