The onkeyup event appears to be malfunctioning

onkeypress seems to be working fine, but I'm having trouble getting onkeyup to work. Any suggestions on how to make onkeyup work properly?

https://jsfiddle.net/btykt0nk/

function isNumber(number_check) {
    number_check = (number_check) ? number_check : window.event;
    var charCode = (number_check.which) ? number_check.which : number_check.keyCode;
    console.log(charCode);
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
<input type="text" onkeyup="return isNumber(event);">

Answer №1

It's important to address this issue using the onkeypress event.

Take a look at this solution

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>
</input>

Answer №2

Instead of using return in this scenario, simply attach your function to the onkeyup event:

onkeyup="isNumber(event)"

function isNumber(event) {
  event = (event) ? event : window.event;
  var charCode = (event.which) ? event.which : event.keyCode;
  
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
     console.log(false);
  }else{
     console.log(true);
  }
}
<input type="text" onkeyup="isNumber(event);">

For better result tracking, use console.log(true) and console.log(false) within your function instead of using return false or return true.

EDIT:

To restrict your input to numbers only, utilize event.preventDefault() along with the onkeypress event. This will ensure that only numeric characters are accepted:

function isNumber(event) {
  event = (event) ? event : window.event;
  var charCode = (event.which) ? event.which : event.keyCode;
  
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
     console.log(false);
     event.preventDefault();
  }else{
     console.log(true);
  }
}
<input type="text" onkeypress="isNumber(event);">

Answer №3

Experience the isNumber event without using the return function. Check out the modifications in your fiddle:

<input type="text" onkeyup="isNumber(event)">
https://jsfiddle.net/btykt0nk/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

vue-form and vue-material are not compatible with each other

In my experience, using a Vue form on a regular HTML <input> element allows validation to work as expected. However, when I switch to using the <md-input> element, the validation no longer functions and an error message is displayed: Element ...

JavaScript encoding the text

Looking for a straightforward JavaScript function to encrypt text data from a textarea using a key (the key being the user's password stored as a hashed session variable, outputted by PHP into a field). The objective is to have the content of the tex ...

Navigating a JSON object using jQuery

My current project involves sending a Json response to an Ajax function within my webpage. The structure of the Json response is as follows: {"one": 21, "two": 10, "three": 19, "four": 100} With this setup in place, I am now in the process of developing ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Error message: "Angular dependencies and provider not accessible"

I recently came across a file upload script on Github that I decided to implement. <script type="text/javascript" src="{% static 'bower_components/angular-file-upload/angular-file-upload.min.js' %}"></script> Furthermore, I have cre ...

Is there a way to asynchronously load multiple textures in three.js using a callback function?

Bringing in a single texture with a callback is a simple task, for instance: var loader = new THREE.TextureLoader(); var texture1 = loader.load("https://i.imgur.com/UiTMJzv.png", process); //executed only once texture1 is loaded function process(){ } B ...

Tips for managing Material-ui's <Autocomplete/> component based on the option's id

When dealing with HTML select in React, it's common to use an id or key to keep track of the selected value: <select value={value} onChange={(event) => setValue(event.target.value)}> {options.map((option) => ( <option value={optio ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

The behavior of TypeScript class inheritance differs from that of its ES6 equivalent

I'm currently developing a custom error handling middleware for my node.js project using express and TypeScript. One key component of this middleware is the AppError class, which extends the built-in Error class. The code for this class is as follows: ...

Is it feasible to relocate an embedded swf file from one tag to another?

My HTML contains two containers for embedded swf files: <div id="player1"></div> <div id="player2"></div> If I load an embedded video into the first div (player1) like this: swfobject.embedSWF("someURL","player1"); Is it possibl ...

Customize Meta tags in Next.js 13.4

I am facing an issue with overriding the meta tag in my RootLayout.js file. Whenever I try to add a new viewport meta tag, it ends up duplicating the existing one. Can anyone help me find a solution to this problem? RootLayout.js <html lang="en&q ...

Is it possible for a MUI control to automatically close itself when clicked outside of the component?

Currently diving into the world of MUI 5 component design. Does anyone know where I can locate the code responsible for closing a component when clicking outside of it? I've searched through the source code but couldn't pinpoint it. This functi ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Using jQuery, retrieve JSON data from a different domain URL, even if the JSON data is not well-structured

Currently, I am utilizing jQuery's ajax function to access a URL from a different domain which returns JSON data. During my testing phase, I've encountered an issue where the presence of multiple '&quot' strings within the JSON valu ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...

How to Retrieve URL Before Closing a jQuery Window Using window.open()?

Is it feasible to retrieve the URL of a window.open window after triggering a window.close event when the user clicks the close button? How can I obtain the last URL visited right before the window closes? ...

What is the best way to add spaces between each element in an array of arrays that are nested within a map

Hello there! I'm seeking guidance on correctly formatting a Multi-Array (an array of arrays) that is nested within a map array. To simplify, I have the following code snippet: const [gradosData, setGradosData] = useState([]) const agregarComa = (grado ...

What is the method for binding context on a click event in Vue?

Can't access context function on click in Vue Example HTML with click function: <li v-on:click="itemClick($event, this)"></li> My Vue.js code snippet: var app = new Vue({ el: '#mainApp', methods: { ite ...

Saving integer data retrieved from DynamoDB in a React Native application

I need to store a user's progress by saving a value in a DynamoDB. While storing the value is not difficult, accessing this value for use in my application has proven to be quite challenging. When using dynamoDBWrapper.getItem(params), where the para ...

"Relating to meteorjs, admin users are akin to those in

Looking for a package or tutorial to create admin users similar to Django. I want to be able to create superusers through the terminal and have the ability to personalize user schemas with Collection2. Additionally, I would like to remove the option for ...