I want to build a website that allows the user to convert Hz
to bpm
(note however that my question concerns all sort of unit conversion). I am using PHP and am hosting my website on Apache.
So, I was wondering if it was possible to "bind" an input field to an HTML element, like we do in WPF developement where you can bind an input area to a WPF element, and apply some sort of data conversion so if the user types 12 bpm
, the bound element will automaticly and immediately display 0.2 Hz
. If the user then adds a "0" so 120 bpm
will be automaticly and immediately converted to 2 Hz
.
The effect I am trying to describe can also be noted on this very forum : as I type my question, I can see a "real-time" final version of my text.
How is this achieved? Is there any way to do it with PHP? I know of AJAX but I would really prefer to avoid using Javascript to hold my math functions. Correct me if I am wrong but I think this could be accomplished with Node.js? Should I consider migrating to Node?
With just the DOM and JavaScript, you can use the input
event on a text field to receive an immediate callback when its value changes as the result of user action:
document.querySelector("selector-for-the-field").addEventListener("input", function() {
// Code here to do and display conversion
}, false);
Example (centigrade/Celsuis to Fahrenheit):
var f = document.getElementById("f");
document.querySelector("#c").addEventListener("input", function() {
var value = +this.value;
if (!isNaN(value)) {
value = (value * 9) / 5 + 32;
f.innerHTML = value;
}
}, false);
<div>
<label>
Enter centigrade:
<input type="text" id="c">
</label>
</div>
<div>
Fahrenheit: <span id="f"></span>
</div>
Stepping back, yes, there are dozens of libraries and frameworks that provide MVC/MVVM/MVM/whatever-the-acronym-is-this-week in the browser. A short list of current popular ones: React, Angular, Vue, Knockout, ... Note that these are not magic, they're just code written in JavaScript (or something like TypeScript or Dart or CoffeeScript that compiles to JavaScript) that use the DOM the covers.