How would you add this to a separate JavaScript file? I started with this but it seems not to work. The console error is Uncaught ReferenceError: isNumberKey is not defined.
<input min='0' type="number" onkeypress="return isNumberKey(event);>
function isNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null :
event.charCode >= 48 &&
event.charCode <= 57;
}
<input min='0' type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57">
I was able to fix my problem by simply doing this. Not sure why .NET was freaking out about how I was calling it with using WebPack.
const Test = document.getElementById("Test");
Test.onkeypress = isNumberKey;
// Prevent pasting (since pasted content might include non-number characters)
Test.onpaste = event => false;
function isNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57;
}
<input min='0' id="Test" type="number" onkeypress="isNumberKey();>
Are you putting the function inside of a script tag? Your code works for me when I do so (you were also missing a closing parenthisis with the onkeypress event)
<input min='0' type="number" onkeypress="return isNumberKey(event);"/>
<script>
function isNumberKey(event) {
return (event.charCode == 8 || event.charCode == 0) ? null :
event.charCode >= 48 &&
event.charCode <= 57;
}
</script>
Edit: to place in a separate file you'd want to add a script tag with a src, like this:
<script src="my-js-file-name.js"></script>
It works fine, but your ternary operator wasn't doing anything other than returning null or boolean, so nothing noticeable was happening. Look what happens when you assign the ternary to a variable and console log it:
function isNumberKey(e)
{
const res = (e.charCode == 8 || e.charCode == 0) ? null : e.charCode >= 48 && e.charCode <= 57
console.log(res)
}
<input min='0' type="number" onkeypress="isNumberKey(event);">