Please input numbers only into the designated field

I am trying to create an input field in my form that only accepts numbers when pasted into it.

For example: If I have some random characters like W123W000 on my clipboard, the input field should only paste 123000.

Note: This solution is currently only functional in Chrome browser.

I have been exploring possible solutions online and have found the following code snippet. However, it does not seem to be working as intended.

var inputBox = document.getElementsByClassName('numbersOnly');
                inputBox.onchange = function () {
                    inputBox.value = inputBox.value.replace(/[^0-9]/g, '');
                }
<input id="number" type="number" class="numbersOnly">

Answer №1

To ensure cross-browser compatibility, utilize jQuery and attach the event input to manage every change.

In Firefox: <input type="number">

Elements automatically reject any input that is not a number (or empty, unless required).

If you switch to type=text, you will lose the specific numeric keypad feature on devices.

var inputBox = $('.numbersOnly').on('input', function(e) {
  e.preventDefault();
  $(this).val($(this).val().replace(/[^0-9]/g, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="number" type="text" class="numbersOnly">

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

A JavaScript code snippet that stores the total number of bytes read from a CSV file in a variable

I currently have a CSV file located on a web server that is regularly updated with numeric and string data of varying lengths. I am seeking a solution to calculate the total byte values of each row when reading the file, as the byte count is crucial due ...

Passing parameters in HTML web applications

My web application is accessible through the link ...:8080/EPQ/. It consists of a single HTML file with the following code: <input type="hidden" name="id" id ="id" > I am looking to pass a value for the 'id' parameter through the URL ...: ...

An error occurred while trying to retrieve a resource from the bower_components directory using Vue.js CLI

I encountered an error in my project when trying to reference CSS and JS files. Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/bower_components/bootstrap/dist/css/bootstrap.min.css This is how my file ...

"Communication breakdown in Vue.js: $emit event not being picked up by corresponding $

Vue.component('rating-edit', { template:` <form> <input v-model="rating.title" type="text"> <textarea v-model="rating.remark">{{rating.remark}}</textarea> <button type="button" @click=" ...

What is the best way to create operating system-neutral file paths in Node.js?

I'm currently fixing issues with my code while running integration tests on an EC2 instance of a Windows machine. Despite resolving the filenames-are-too-long problem, several paths remain unresolved due to being hardcoded for UNIX systems. I've ...

Tips for transferring data from one tab to another tab using Greasemonkey

Is it possible to extract data from a webpage in one tab and then input it into a textarea on a different page opened in a separate browser tab using Javascript and Greasemonkey? ...

An HTML/CSS component that dynamically adjusts its height at random intervals

My goal is to have the footer of my page occupy just one line in height. On occasion, when I open my page in a new browser tab, the footer ends up being two lines tall. However, if I simply reload the page within the same tab, everything appears as intende ...

Implement an innovative solution to automatically close the navbar component in tailwindcss on

I've been attempting to create a unique tailwind navbar component for React, but I've encountered issues when trying to make it close on scroll for mobile view. I found the initial code on this website. After that, I tried implementing the code ...

Transform a Mongoose object into a specific JSON schema

When retrieving data from MongoDB using mongoose as an ORM, I have a specific requirement. Instead of sending all the fetched information back to the client in the response, I need to convert the mongoose object into a JSON object that adheres to my cust ...

Using JQuery and Bootstrap, add or remove rows dynamically

For my project, I am creating tests (in English, physics, etc.) using JSTL, Bootstrap, and jQuery. I need a form to create a Test with questions and answers. However, I am facing an issue. When I try to delete a question, the answers that were added are no ...

When a form input is submitted, the webpage will refresh with a new

I have a form embedded on my WordPress page. I want to identify users without referrers so that I can set the referrer for them automatically (the referrer part is handled by a plugin). The registration form URL looks like this: The code provided below w ...

Automatically Assigning a Default Value to a Column Using SEQUELIZE ORM

When fetching data from a database using Sequelize ORM, I need to set a default value. Here is an example of the SQL query: SELECT a.affiliate_id, a.active AS current_state, IF(MAX(cn.contract_id) IS NULL ,0, IF(DATEDIFF(NOW(),MAX(cn.contract_date) ...

What is the best way to select an element based on its relationship to another Element object using a selector?

I am currently developing a small library in which I require the ability to select a relative element to the targeted element using the querySelector method. For instance: HTML <div class="target"></div> <div class="relative"></div& ...

Having trouble with protractor's sendKeys function when trying to interact with md-contact-chips

Does anyone know how to set a value using sendKeys in Protractor for md-contact-chips? I attempted to use element(by.model('skills')).sendKeys('Java'); but it doesn't seem to be working. Any suggestions on how to approach this in ...

A guide on utilizing getStaticProps to map a collection obtained from Strapi within a Next.js component

I'm currently following a tutorial on YouTube that teaches how to create a basic blog using Next.js and Strapi. The code snippet below is used to fetch post data from Strapi, but it's not working as expected because the .map function can only be ...

problem with overlapping elements

Hey there! I'm facing a CSS issue where an error message appears below the contact us box if the user doesn't fill the text box properly. However, there's an overlap issue with the image below the contact us box. Any suggestions on how to s ...

Parsing JSON or eliminating double quotation marks in data acquired from a model or database within the Rails framework

foo.html.erb <script type="text/javascript"> var all_user_data = <%= @user.all_user_bar_chart.to_json.html_safe) %>; </script> abc.js $(function () { if ($("#foo").length > 0){ var user_charts = new Highcharts.Chart({ ...

Can Webpack effectively reduce the size of jQuery files?

While this question may seem basic, I have yet to come across a direct answer to it. My dilemma is whether or not to continue utilizing jQuery in my React application, primarily for AJAX purposes. Will webpack intelligently include only the necessary AJA ...

I am looking to integrate a function into an ejs page using a node.js app and express, but I need to ensure that it does not execute

I am currently developing an application in node.js, utilizing mongoose and express. My goal is to pass an asynchronous function that triggers the opening of a browser window using puppeteer to an ejs page, and execute that function only upon clicking a bu ...

Scrolling to an element is not possible when it has both position absolute and overflow-x hidden properties

My issue involves animating ng-view with a slideup animation, requiring absolute positioning of elements and overflow-x: hidden to clip the content. However, I need to use the scrollTo element functionality on one sub-page, which doesn't work when bot ...