I have an HTML input for which I want to limit the possible to 100 when manually entering, I have a min and a max so that if they use the spinner (up and down arrows) it limits it already. To do this, instead of using Inline Javascript, I wanted to call a function that could be used for several functions throughout my HTML file.
Wanted Functionality:
<input id="..." oninput="foo()">
...
<script>
function foo() {
if(this.value > 100) {
this.value = 100; // If the inputted value is 99, do nothing, if it's 999, change it to 100
}
}
</script>
I wanted a functionality like this, which would let me this this.value - however - this.value is not accessible (I think???) from within the foo function.
So I tried doing this:
<input id="..." oninput="foo(this.value)">
...
<script>
function foo(value) {
if(value > 100) {
value = 100;
}
}
</script>
But I think only the "copy" of value gets changed to 100, not the actual value. So I was able to do it by returning a value like this:
<input id="..." oninput="this.value = foo(this.value)">
...
<script>
function foo(value) {
if(value > 100) {
value = 100;
}
return value;
}
</script>
but this code seems quite clumsy, is there a better way to do this?
EDIT: SOLVED! Thank you all for the answers, this is my code now! I also parse the input to make sure that it's ONLY numbers, no "e" or "." because all I care about are integers.
<input id="area-level-input" type="number" value="1" min="1" max="100" oninput="limitInput.call(this, 100)" onkeydown="isValidNumberEntry()">
Where the respective functions are:
function limitInput(limit) {
if(this.value > limit) {
this.value = limit;
}
}
function isValidNumberEntry() {
// keyCode 8: Backspace; keyCode 46: Delete
return (event.keyCode === 8 || event.keyCode === 46) ? true : !isNaN(Number(event.key));
}