I would like to know if you can do addition or subtraction or any basic operation in real time on a web page.
I mean not having any button, that when you enter the data in a textbox or an input (since what I am developing is web) the result of the mathematical operation automatically appears in a label.
I've been looking for some things in JavaScript, or alternatively AJAX calling a PHP script, but haven't been able to find anything.
An AJAX call could be made to PHP to return the result. However, I think it's much easier to do it directly in JavaScript.
To perform a calculation in JavaScript, we must use the function
eval()
, which could bring security risks. For that, we perform a minimal check, to ensure that the only characters you enter are digits or mathematical signs.Edit: After re-reading your post, I thought you might also be asking for a way where I can enter a math expression and have it solve in real time. In that case, I recommend that you go through the following page and learn
eval
about the Math.js function :Here is a sample of how it works:
The events
onchange
,onkeydown
(which is the best replacement for the deprecatedonkeypress
) andkeyup
(which works best for detecting a keystroke-to-keystroke change), etc... are common to all DOM elements, so they are available in the labels<input>
. These events must be implemented in the web interface, not in the PHP engine.Here's an example of how to do it using
onchange
andkeyup
:You can use AngularJS to create reactivity while the user enters the operation data. In this case, add and subtract.
I used the shared code to perform the mathematical operations from js, it works perfectly, in my specific case I am extracting the VAT and the total of an amount and a unit value, but I have the following problem, I load fields dynamically, this means that I create several fields to apply this function and it only applies it to the first field. How do I make this function apply to all the fields called num1 and num2 ?