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

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Acquire information from a Card using Oracle Apex

I have a Card Regions that showcases some of my tables. I'd like each card to redirect to a specific page based on a number (the "page_table" number corresponds to the page it will redirect to). Below is the Query for the Cards Region: SELECT table_n ...

I am unable to integrate Autoprefixer into an Express project

I am having trouble adding Autoprefixers to the postcssmiddleware, as mentioned in the documentation here I also attempted using express-autoprefixers but still cannot see the vendors in my dest or public folder. You can find a link to my repository (node ...

Encountering a 500 server error while trying to send an email using SendGrid in conjunction

Seeking help on integrating an email capture form into a NextJS site by following this tutorial: Simplified the form to only include the email field. The content of my api/contact.js file is as follows: const mail = require('@sendgrid/mail'); ...

React: "The function is not toISOString"

I am currently working on a Todo List project using Next.js. As part of the functionality, I am trying to implement a due date feature. However, when I make a post request, I encounter the following error: Unhandled Runtime Error TypeError: dueDate.toISOSt ...

Controller function failing to trigger

I'm new to asking questions, so if I've made a mistake, please let me know. I've searched for an answer here but couldn't find one. Any help would be greatly appreciated. I'm attempting to load a list of "Countries" using a contro ...

JQuery is failing to parse JSON data

I've written a script to fetch data and display it in an HTML table. Here is the script: $('#search_filter_button').click(function (e) { e.preventDefault(); // Prevent form submission var county = $('#filter_county').val() ...

Production environment experiencing issues with Stripe functionality due to element remaining mounted

When making a payment in development mode, everything goes smoothly. However, when I switch to production, I encounter the following error message: v3:1 Uncaught (in promise) IntegrationError: We could not retrieve data from the specified Element. Please e ...

What is the most efficient way to use the $slice operator on a highly nested array in mongoose

I am currently working on slicing a deeply nested array. To illustrate, consider the following structure. I aim to slice this array for pagination purposes. {messages: [{ message: { members: [ {example: object, blah: blah}, {example2: object2, blah2: blah ...

Issue with disabling checkboxes in jsTree

Currently utilizing the latest version of jsTree in one of my applications. I would like to have specific checkboxes disabled by default. To achieve this, I am referencing this resource. The jstree code I am using is as follows: $("#"+"div_"+aspectid).js ...

Ways to implement varying services based on route parameters

Imagine having two services with similar APIs but different implementations. myApp.module('myModuleApp').service('BananaService', function() { this.name = 'banana'; }); myApp.module('myModuleApp').service(&apo ...

Troubleshooting Issue with Nested ng-include in AngularJS: Difficulty arises when the parent element with the ng-include attribute is dynamically added using the ng-

Click here to see a demo plunker that will help you understand my issue. On my main page, I have a table. Each table row is followed by a hidden empty row. When the first row is clicked, I use a directive to inject HTML into the empty row below it. Main ...

Error: The current element cannot be clicked. Please try again

I have been attempting to trigger a click event on another button within an onClick event function. An error occurred: Uncaught TypeError: this.clickBack.current.click is not a function The React version being used is 16.8.6 constructor(props) { s ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Utilize flexbox to create a list that is displayed in a column-reverse layout

I am facing a challenge in displaying the latest chat person in the 1st position (active) using Firebase. Unfortunately, Firebase does not have a date field which makes it difficult to achieve this. I have attempted converting the date into milliseconds an ...

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

How to modify a specific property of an array object in JavaScript

I have an array of objects that looks like this: [ { number: 1, name: "A" }, { number: 2, name: "e", }, { number: 3, name: "EE", } ] I am looking for a way to insert an object into the array at a specific position and ...

Tips for adding elements to an angular $scope.array?

Currently, I am facing an issue that I cannot seem to pinpoint (most likely due to my limited expertise in AngularJS). In my HTML file, I have a basic ng-repeat set up like this: <ul> <li ng-repeat="fot in fotografia"><img src="{{fot.path ...

The error message received states: "materialize-css Uncaught TypeError: Vel is not defined as

My current setup involves webpack as the bundler/loader, and I've successfully loaded materialize css (js/css). However, when attempting to use the toast feature, an error is thrown: Uncaught TypeError: Vel is not a function The library is being inc ...

Creating a many-to-many relationship in Sequelize using a join table to insert data

I recently set up two models in sequelize with a many-to-many relationship. While Sequelize successfully created the join table, I am facing difficulties when trying to insert data into it. Despite going through the documentation section on associations ...