JSFiddle - React, Tailwind, and code Playground
by Laura
HTML
<div class="col">
<p>This input is type=number, so it will only save strings of numbers or empty strings.</p>
<p>Try typing an integer, then a word.</p>
<input id="myIn" type="number" min="1" max="50" style="min-width:50px" />
<p id="msg"></p>
</div>
<div class="col">
<p>This input is type=text, so it will save all inputs.</p>
<p>Try typing an integer, then a word.</p>
<input id="myIn2" type="text" onkeyup="TestThis(this.value)" style="min-width:50px" />
<p id="msg2"></p>
</div>
CSS
div.col {
float: left;
margin: 0 30px;
max-width: 200px;
}
JavaScript
// My custom imutation of console.log()
function Log(text, p) {
document.getElementById(p).innerHTML = text;
}
// This function uses the parameter "rawNumber" as a variable, but also uses an extra variable "number"
function TestThis(rawNumber, p) {
// Convert the input (string) to integer
// parseInt returns NaN or integer. Truncates decimals
var number = parseInt(rawNumber);
// Check to see if the result is NaN or is an integer
if (isNaN(number)) {
Log(rawNumber + " is not a number.", p); // Log is my imitation of console.log()
}
// will run if number is type int
else {
if (number > 0 && number <= 100) {
Log(rawNumber + " is a valid number.", p);
} else {
Log(rawNumber + " is not between 1 and 100.", p);
}
}
}
// Event listeners
document.getElementById("myIn").addEventListener('input', function () {
TestThis(this.value, "msg");
});
document.getElementById("myIn2").addEventListener('input', function () {
TestThis(this.value, "msg2");
});