Is there a way to disable the backspace keycode in an input field?

I need to disable all keys in input field, this is what I have so far

window.onkeypress = function(event) {
  event.preventDefault();
  if (event.charCode && (event.charCode < 48 || event.charCode > 57)) {
    return false;
  }
}
<input type="text" value="1" size="4" max="7" name="people-value" id="adults-value">

Why does the backspace key still work with this code? What other events should I consider using?

Answer №1

Depending on the web browser you are using, the keypress event is typically triggered when a key is pressed down and that key can produce a character value.

As backspace does not generate any visible output, it does not trigger the keypress event.

Instead, you can utilize the keydown event for this purpose.

window.onkeydown = function(event) {
  event.preventDefault();
  console.log(event.charCode)
  if (event.charCode && (event.charCode < 48 || event.charCode > 57 || event.charCode > 48)) {
    return false;
  }
}
<input type="text" value="1" size="4" max="7" name="people-value" id="adults-value">

You can view an example demo on JSFiddle here: https://jsfiddle.net/L47k7uwx/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

Two full screen divs aligned side by side using float:left

Looking for a way to create UL or DIV elements where each list item/child div takes up the full screen space (100% width, 100% height) and is floated left for horizontal scrolling. Here's my code, but it's not working as expected: HTML: <htm ...

The submit form and cordova functions are failing to trigger

I am encountering an issue where I cannot successfully call the submitForm() function when attempting to trigger it via ng-submit. The function does not execute as expected. How can I troubleshoot and resolve this problem? (function () { 'use str ...

Mall magnitude miscalculation

I am currently experiencing an issue with Galleria and the Flickr plugin. Some images are displaying correctly, while others appear scaled and parts of them are cut off. How can I fix this problem? Below is the HTML code for the Galleria gallery on my web ...

What is the best way to programmatically insert new rows into a table

I am currently working with the foundation 5 framework (not sure if this is relevant). I need to ensure that each CELL is treated as a distinct item/value when passing information to another page, and I am unsure of how to approach this issue. It should cr ...

Automatically adjust the size of input control text based on the screen dimensions

I am facing an issue with resizing the text inside an input control when the window is resized. The problem occurs between the width range of 1032px to 575px, where the text inside the input control does not display completely. However, below 575px width, ...

Using FB Messenger iOS to verify a third-party app

I am in the process of creating a web application that features Facebook authentication and the capability to invite friends through Facebook. While working on this project, I encountered a specific issue that is quite frustrating and I am hoping someone o ...

How can I make a Vue component close when clicking outside of it?

I am searching for a solution to automatically close a component when there is a click outside of the element. I attempted to use an addEventListener for this purpose. Although it successfully closes the component, it encounters an issue where it fails to ...

Having Trouble with Updating Variables in AngularJS Service

I am faced with a challenge involving a series of images displayed side by side. My goal is to determine which image has been clicked, retrieve the relevant information, and display it in a modal window. HTML Markup <section class="portfolio-grid ...

What is a dynamic component in Vue with Typescript?

I need help implementing type checking for my dynamic component instead of relying on 'any' as a workaround. Can someone guide me through the proper way to achieve this? <script> ... interface { [key: string]: any } const pages: page = ...

exploring div element(s) with jQuery

My HTML page contains multiple div elements in the body. I have also included buttons with associated click functions in jQuery to change the background-color of a div element based on the button pressed. However, I'm facing an issue at the 'term ...

Utilizing ng-repeat, filter, and the uib-popup-datepicker to refine and display specific data within a table column

I'm currently facing a common scenario in my Angular application where I need to filter items from an ng-repeat using an HTML5 input of type 'date' or Angular-UI-Bootstrap's 'uib-popup-datepicker'. Despite extensive research, ...

Retrieve the div element by calling a scriptlet with JavaScript

I am facing an issue with a web page that includes a scriptlet like this: <div id="flash_chart"> <%=content_data['report_text']%> </div> The variable content_data['report_text'] contains a lengthy string ...

Contrast between the expressions '$(<%= DDL.ID %>) and $('<%= DDL.ID %>')

I spent hours trying to attach an event to a drop-down list with no success. I even sought help in a JavaScript chat room, but couldn't find a solution. However, by randomly attempting the following code: $('<%= ddl.ID %>').bind(&apos ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

Utilizing the column approach within Protractor

I've been going through the documentation trying to figure out exactly what the column method does, but I can't seem to find a clear explanation. Can anyone shed some light on its functionality? Here's the code I'm working with: var p ...

Mobile browser unable to show FB App

I created a fan-gate app for my page and it is working flawlessly on web browsers and my iPad browser. However, when I try to access it on my android mobile browser, I receive an error message saying "this page cannot be displayed." What could be causing ...

Setting a custom background image in HTML using the designated file PATH

My current issue involves the inability to set my background photo using a CSS file. I am utilizing NetBeans for this project. Inside a folder named css, there is a file called global.css which contains the following code: body{ background-image: url ...

Tips for updating the color of an active navbar:

<div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item mx-4"> <a class="nav-l ...

Troubleshooting Owl Carousel's width problems upon initial loading

Currently, I am utilizing the Owl Carousel and have the following script: $("#owl-demo").owlCarousel({ items : 3 }); My intention is for the container to display 3 images. However, upon initial load, this is what appears: https://i.sstatic.net/ePLAQ. ...

The node rejected the style application due to its MIME type ('text/html') not being a compatible stylesheet MIME

My goal is to serve a static index.html file along with main.css using this node server implementation: The following code can be found in the serve.js file: var express = require('express') var cors = require('cors') var app = expre ...