onkeypress() method not triggering the function

I have a task to prevent users from typing "%" in a textArea, so I implemented the following:

However, even after clicking inside the text area, I can still type '%', indicating that my onkeypress function is not working properly or there is an issue with the function itself.

$scope.test = function() {
  var txtarea = document.getElementById("exampleFormControlTextarea1");
  txtarea.addEventListener("input", function() {
    txtarea.value = txtarea.value.replaceAll("%", "");
  })
}

I also tried another approach:

function myfunction () {
        var txtarea = document.getElementById("exampleFormControlTextarea1");
        txtarea.addEventListener("input", function() {
            txtarea.value = txtarea.value.replaceAll("%", "");
        })
    }
<div class="col-md-12 label-base">

  <label for="exampleFormControlTextarea1">Justify</label>
  <textarea style="resize: none" ng-disabled="negociacaoEspecCtrl.proposta.flagDesabilitaEdicaoProposta"
  class="form-control observacoes" id="exampleFormControlTextarea1" rows="3" 
  ng-model="negociacaoEspecCtrl.proposta.dadosCadastro.negociacaoEspecial.justificativaNegociacaoEspecial"
    onkeypress="test()"></textarea>
</div>

Answer №1

It seems like you're in need of the ngKeypress directive.

You can trigger a function on ngKeypress by following this example. I've changed the ng-model object to 'model' for simplicity's sake, as your original one was quite lengthy.

<div class="col-md-12 label-base">

  <label for="exampleFormControlTextarea1">Justify</label>
  <textarea style="resize: none" ng-disabled="negociacaoEspecCtrl.proposta.flagDesabilitaEdicaoProposta" 
  class="form-control observacoes" id="exampleFormControlTextarea1" rows="3" 
  ng-model="model"
    ng-keypress="test()"></textarea>
</div>

Since the textarea is linked to an ng-model, make sure to adjust your method accordingly:

$scope.test = function() {
   console.log("Method called");
   $scope.model = $scope.model.replaceAll("%", "");
}

Answer №2

Referencing this solution:

Implement a filter in conjunction with an ng-change function, similar to:

angular.module("example", [])
    .filter("cleaner", function() {
        return function(input) {
            return input.replace(/%/gi, "");
        }
    }).controller("exampleController", function($scope, cleanerFilter) {
        $scope.onChange = function() {
            $scope.specialNegotiationCtrl.specialProposal.dataEntry.specialNegotiation.justificationSpecialNegotiation = cleanerFilter($scope.specialNegotiationCtrl.specialProposal.dataEntry.specialNegotiation.justificationSpecialNegotiation);
        }
    })

and apply it to your element:

<textarea ... 
ng-model="specialNegotiationCtrl.specialProposal.dataEntry.specialNegotiation.justificationSpecialNegotiation"
ng-change="onChange()"></textarea>

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

Solving problems with Vue.js by effectively managing array content and reactivity issues

In the past, it was considered a bad practice to use the following code snippet: array = []; This was because if the array was referenced elsewhere, that reference wouldn't be updated correctly. The recommended approach back then was to use array.le ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

Selenium Python Slider Button Element Visibility Issue

Currently, I am developing a parser to automate the process of clicking buttons on a website. However, I am encountering difficulties in clicking two specific buttons. The buttons I am aiming to click are "Elija el imports a financiar" and "Elija la mensu ...

Transforming JSON data from a Javascript object into Ruby

When I send an object from Javascript to a Sinatra POST route, I use the 'stringify' method to convert the JS object to JSON. The JSON that is being sent looks like this (based on the Chrome developer tools): {"a":1,"b":2,"c":"3"}: In my Sinatr ...

Track your status with jQuery technology

I have a link: <a href="/test/number/3/phone/0">33df</a> Is there a way to determine if the words 'number' and 'phone' are present in this link? I am looking for a function similar to: check('number', ' ...

Is it possible for me to create a Pomodoro clock similar to this one?

Can you provide guidance on creating a Pomodoro clock similar to this design: https://i.sstatic.net/qhd1Z.png As time progresses, the arrow should move around causing the circumference of the circle to increase. What approach or library would you recomm ...

Is there a problem connecting to the MongoDB server?

I am having trouble connecting to the MongoDB server using the link provided below. I have double-checked the password and dbName, but it still won't connect. Can someone please assist me with this? const mongoose = require('mongoose'); ...

Utilizing Async.each fails to trigger the ultimate callback function

Here's the scenario: I expect the function finalCallBack to be triggered after we finish looping through all elements. var rows = [ { name: 'first'}, { name: 'second'} ]; var execForEachRow = function(row, callback){ var ...

When utilizing npm install buefy and npm install font-awesome, there may be an unnecessary display of [email protected] and [email protected] extraneous errors

After installing buefy and font-awesome, I noticed that it is marked as extraneous and the folder appears with an arrow icon but is empty. How can this issue be resolved? For example: +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

How can you stop VueUse useStorage from filling localStorage again after clearing it?

Using Vue 3 in combination with VueUse's useStorage to sync reactive state with localStorage has presented a challenge for me. Whenever I programmatically clear localStorage during user logout processes, it seems to automatically refill with previous ...

Tips for effectively monitoring scope for data loading

I have successfully created a custom Angular directive that utilizes D3.js to create a visualization. In my HTML, I reference this directive as follows: <gm-link-analysis data="linkAnalysis.connections"></gm-link-analysis> The relevant part o ...

Tips for organizing the outcome of a seamless web scraping operation with Apify and Puppeteer

Extracting data from a table on the designated URL using Apify and Puppeteer is my current goal: https://en.wikipedia.org/wiki/List_of_hedge_funds The desired outcome should be an array of objects. Each element in the array must represent a <tr> ro ...

How to output a string in jQuery if it includes a certain character?

I need to extract all strings that include a specific word within them, like this: <div> <div> <span> <h3>In Paris (Mark Bartels) worked for about 50 years.</h3> </span> </div> ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...

GET request body parameters are not defined

Can anyone help me with retrieving the parameters of a GET request? I've tried various methods but everything keeps logging out as 'undefined': GET // Looking for a list of Players $scope.find = function() { $scope.players = Players.qu ...

Reorganize Material UI Grid Items with varying lengths

I'm currently working with a Material UI grid system that appears as shown below: <> <Typography gutterBottom variant='h6'> Add New User{' '} </Typography> <Grid container spacing={3} ...

Using the className prop in a React Component

Struggling to assign a classname to the material-ui Button component. Here are my failed attempts: Attempt 1: attributes.map((attribute, index) => { const classString = 'classes.button' + index; console.log(classString) return ( &l ...

Creating a "Container" component in Vue.js step by step

As a newcomer to Vue, I am facing a challenge in implementing a wrapper component similar to React's 'Wrapper' component. Specifically, I want to create a reusable datagrid component using a 3rd-party some-table component and a pagination co ...

Retrieve only the items from a JavaScript array where the index is below a specified value

My goal is to filter out all the items from the initialItems list that have an index lower than the current item. For example, if the current item is CM, I want to display QS, IT, and AB in a draggable dropdown menu. However, I'm unsure of how to prop ...

Utilize button element with both href and onClick attributes simultaneously

I'm in the process of preparing a button that includes href and onClick. After testing it on my local environment, everything seems to be working smoothly. Do you know of any specific browsers that may encounter issues with this setup? <Button cl ...