How can I specifically activate the keydown event for alphanumeric and special characters in Angular7?

I am looking to create a keydown event that will be triggered by alphanumeric or special characters like #$@.

  <input type="text" style="width: 70%;" [(ngModel)]= "textMessage" (keydown) ="sendTypingEvent()" >

However, I want to prevent the event from being triggered by keys such as enter, escape (esc), shift, alt, tab, backspace and command (meta), arrows, and function keys (f1 through f12).

Is it possible to set up a REGEX pattern directly in the HTML?

<input (keydown.a)="..."> --expect to trigger

Currently, I can filter out unwanted keys within the event handling function as shown below. But I am exploring other options.

sendTypingEvent(event) {
  if (event.key === "Enter" || event.key ==='esc' .... ) {
    console.log("skip this event");
  }

}

Answer №1

Below are two methods for restricting the keydown event:

  1. Allow only alphanumeric key presses
sendTypingEvent(event){
        if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90)){
            console.log("input was 0-9");
            console.log("input was a-z");
            return true;
        }

        return false;
    }
  1. Restrict specific keys
sendTypingEvent(event){
        if ((event.keyCode >= 112 && event.keyCode <= 123) || event.keyCode == 16){
            console.log("Disabled f11 to f12, shift keys");
            return false
        }
}

For more information on Keycodes, visit -

Answer №2

document.getElementById("myinput").addEventListener("input", function(event) {
  if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.data)) {
    console.log(event.data) // or
    // your operation
  }
})
<input id="myinput" type="text" style="width: 70%;">

If you need to display only special characters in the console, modify your trigger function as shown below:

sendTypingEvent(event) {
  if (/[!'^+%&/()=?_\-~`;#$½{[\]}\\|<>@,]/gi.test(event.key)) {
    console.log(event.key);
  }
}

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

Eslint is unable to locate file paths when it comes to Solid.js tsx extensions

Whenever I attempt to import TSX components (without the extension), Eslint raises an error stating that it's unable to resolve the path: However, if I add the TSX extension, it then prompts me to remove it: This represents my configuration in .esli ...

The Angular Material side navigation module is not being acknowledged

Currently, I am utilizing Angular version 9.1.11 in conjunction with Angular Material version 9.2.4. The issue arises when attempting to import the MaterialSidenavModule, which is required for utilizing components like mat-sidenav-container. Below is a sn ...

How can I simulate the response of a VueX action using Vue-test-utils?

I am currently developing a test for a Vue component that interacts with a module store to execute an action and utilize the result from it. Since the action involves making requests to our API, I prefer not to run the test using the actual action. Instea ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

establish expiration date for image

On my e-commerce site, users upload images to customize product items, such as adding their photo to a cake. I'm curious if there's a way to automatically delete these images after a certain expiry date. Is it possible to implement an automatic ...

JavaScript JSON YouTube API viewCount function is not functioning correctly

I'm struggling to retrieve the views of a video using JavaScript (Chrome Extension). Here is the code I have so far: $(function() { $.getJSON('http://gdata.youtube.com/feeds/api/videos/H542nLTTbu0?alt=json',function(data) { ...

Refreshing manually will display only the JSON data

Utilizing a NodeJS server to fetch information from a MySQL database and presenting it as a JSON object is the task at hand. app.get('/random', (req, res) => { var connection = mysql.createConnection({ host: 'localhost', ...

What is the best way to define a variable that captures and logs the values from multiple input variables?

Hey there, I'm a new coder working on a shopping list app. I'm trying to display the input from three fields - "item", "store", and "date" - at the bottom of the page as a single line item. I attempted to do this by creating a variable called "t ...

How can I programmatically adjust the center of a Google Maps v3 map?

I have a table with 2 columns. The first column contains a div with a Google map, while the second column has a panel that changes its width after a few seconds. On the map, there is a marker placed. Issue: When I click on a button that triggers setCente ...

Determine whether AngularJS directive method binding automatically defaults to angular.noop

In my directive, I am passing a function to a plugin which will use it with a specified value. Let's simplify things by ignoring data changes: angular.module('some.directives', []) .directive('myDirective', [, function () { ...

Is it possible to utilize localStorage.getItem within Next.js while using redux toolkit?

While I successfully used localStorage.setItem() inside the redux toolkit slice, I encountered an issue when trying to use localStorage.getItem(). The error message "local storage is not defined" popped up, preventing me from accessing the stored data. imp ...

The promise node design pattern

I'm dealing with a node issue where I need to call a Data Access Object and possibly others within it, and then render a Jade template once everything is done. Here's an example of what I want to achieve: provider1.getData(args, function(error ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

The date format adjustments vary depending on the web browser being used

I have a JavaScript function that displays the date in the browser, but the format changes depending on the browser. For example, when I open my project in Chrome, the format is 4/30/2015, but when I open it in IE, it's displayed as 30 April, 2015. Ho ...

Error: The use of "let" as a lexically bound identifier is not permitted

Currently working with vue.js and encountering the error message "Uncaught SyntaxError: let is disallowed as a lexically bound name". When trying to troubleshoot, I'm faced with a blank screen and this error appearing in the console. I've search ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

Having trouble triggering a click event with JQuery

I have a hidden link for downloading Audio Files that I want the user to access using a button. However, I am having trouble triggering the click event. Below is the HTML code: <a class="APopupDown" data-icon="home" id="DownloadFile" href="http://yaho ...

Using jQuery to Check Cookies and Hide Content Depending on the Value and Data Attributes

On a webpage, I have a collection of coupons with unique data attributes (data-coupon). Currently, I am using cookies to store the value associated with each coupon (ranging from 1 to 4). While my code is functional, it feels repetitive and cumbersome. S ...

React Project Encounters NPM Installation Failure

I recently started delving into the world of React and experimenting with different examples. Everything was running smoothly until I attempted to start the server [npm start] and encountered an error as shown below. Despite my best efforts, I can't p ...

Utilizing NodeJS alongside Express to retrieve JSON response on the Client side

Currently, I am facing an issue with my Express server where I am struggling to properly read the information sent to the client as part of the response. One of the endpoints in my server is defined as follows: app.post('/click',(req, res) => ...