I have stumbled upon this particular code, and while I find it to be fully functional, I am trying to nitpick several parts of it in order to make it more user-friendly. That being said, I am trying to force some values in every textbox.
The first textbox is supposed to be a binary-only textbox, only 0s, and 1s allowed. The second and fourth textboxes are supposed to be octal and hex-based ones. My question is, how do I force rewrites on those textboxes? What I am trying to say is that I am looking for a property or event that erases my input if it doesn't match I want in the textbox.
If I type a letter or a number in the binary textbox, it should be erased. If I type a number greater than 7 or a letter in the octal textbox, erased. Hexadecimal = no letters other than A-F. And for decimal, no letters. I know how to exclude those values using and if and other nomenclatures, but I am truly lost when it comes to doing it for every textbox.
This is the code:
window.onload = id;
function id(id) {
return document.getElementById(id);
}
function Convert(s, n)
{
if(parseInt(id(s).value, n))
{
if("bin" != s) { id("bin").value = parseInt(id(s).value, n).toString(2) }
if("oct" != s) { id("oct").value = parseInt(id(s).value, n).toString(8) }
if("dec" != s) { id("dec").value = parseInt(id(s).value, n).toString(10) }
if("hex" != s) { id("hex").value = parseInt(id(s).value, n).toString(16) }
} else
{
if("bin" != s) { id("bin").value = "" }
if("oct" != s) { id("oct").value = "" }
if("dec" != s) { id("dec").value = "" }
if("hex" != s) { id("hex").value = "" }
}
}
Use the onkeyup event to listen to changes made by the user in an input box.
You could check with a REGEX expression that the string in your input box only contains 0s and 1s. If not then remove the last inputted letter:
const check = e => {
const value = e.target.value
const isBinary = /^[0,1]+$/.test(value)
if(!isBinary) {
e.target.value = value.substring(0, value.length - 1);
}
}
<input onkeyup="check(event)">
Where /^[0,1]+$/.test(value) will return true if value only contains 0 and/or 1, else it will return false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With