So that is what you have:
let interestInput = document.querySelector("#interestInput")
interestInput.addEventListener("change", () => {
interestInput.value = `${interestInput.value}%`;
});
Interest: <input id="interestInput">
You are using the change
event, which occurs when the user leaves the input field. That is just adding the %
sign...
So if you want the user to type in a percentage (a number with 2 decimal places) on "keypress" (I suggest the keyup
event), that you be something like (see comments within the code):
let interestInput = document.querySelector("#interestInput")
interestInput.addEventListener("keyup", function() {
// Just for this demo...
console.clear()
// Get the input value
let value = this.value
console.log(value)
// Maybe it already is formatted with a decimal point and a %
// so remove the dot and %, then parse as an integer
let number = parseInt(value.replace(/[\.\%]/g,""))
console.log(number)
// Divide by 100
let percentage = number/100
console.log(percentage)
// change the input's value
interestInput.value = `${percentage}%`;
});
Interest: <input id="interestInput">
The same thing shortened in a one-liner:
let interestInput = document.querySelector("#interestInput")
interestInput.addEventListener("keyup", function() {
this.value = parseInt(this.value.replace(/[\.\%]/g, "")) / 100 + "%";
});
Interest: <input id="interestInput">
About this /[\.\%]/g
weird part, you can read about Regular Expressions and play with Regex101