Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
Inline JavaScript to separate JavaScript file

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">

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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();>

about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report

0

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);">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!