Ng-keydown event not refreshing input field

When working on this code snippet, I encountered an issue where I could not update or enter a new value in the input field if the current value was 0. No matter how much I tried to change it, the input field value remained the same.

Even when deleting the existing value and replacing it with something else, the value stayed unchanged.

Below is the HTML code:

<input ng-model="lineitemDetailsCtrlAs.lineItems.orderedQuantity" type="text" class="col-md-6 text-right panel-row-spacing"
                ng-keydown="valueChanged($event)" required
                />

The corresponding angular code is as follows:

$scope.valueChanged = function (event) {
 var quantityRequire={};
    if (event.keyCode === 48 || lineitemDetailsCtrlAs.lineItems.orderedQuantity == 0) {
            quantityRequire = {
              "messageId": "ORDERED_QUANTITY",
              "params": [],
              "severity": "ERROR"
            };
            lineitemDetailsCtrlAs.errorMessages.push(quantityRequire);
          }
          else{
            event.preventDefault();
          }
    };

Answer №1

By using "event.preventDefault();" you are preventing the event from continuing, as only keycode 48 (representing the number 0) is allowed. Any other key events will trigger the else condition and halt the input value update process.

Answer №2

I agree with Rameshkumar Arumugam's analysis of the code issue. Here is a corrected version:

angular.module("myApp", [])
  .controller("MainCtrl", function($scope) {
    $scope.lineItems = {
      orderedQuantity: 12
    };
    $scope.errorMessages = [];
    $scope.valueChanged = function(event) {
      var quantityRequired = {};
      if (event.keyCode === 48 || $scope.lineItems.orderedQuantity == 0) {
        quantityRequired = {
          "messageId": "ORDERED_QUANTITY",
          "params": [],
          "severity": "ERROR"
        };
        alert(quantityRequired["messageId"]);
        $scope.errorMessages.push(quantityRequired);
      }
    };
  })
<div ng-app="myApp">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  <div ng-controller="MainCtrl">
    <input ng-model="lineitemDetailsCtrlAs.lineItems.orderedQuantity" type="text" class="col-md-6 text-right panel-row-spacing" ng-keydown="valueChanged($event)" required />
  </div>
</div>

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

Initiating an AJAX request to a JSP file

Attempting to make an ajax call to a jsp page as shown below: $(document).ready(function () { $('#photo').photobooth().on("image", function (event, dataUrl) { alert(dataUrl); //alert($('#mygroupuserid')); ...

Discovering variances among n sets of objects

Within my code, I have an array named props that consists of multiple arrays containing objects. All the arrays have the same number of objects. Each object in the arrays has four properties: participation_enabled, name, pathing_enabled, and id. These pro ...

Are these two sections of my code distinctive in functionality? Do they both address potential errors in the same manner?

After receiving some helpful suggestions on my code from a user on stack overflow, I decided to revisit and make improvements. However, I am now questioning whether the changes I made handle errors in the same way as the original code. This is my initial ...

Having trouble choosing a subitem from a dropdown menu in Vuejs?

An example can be found at https://jsfiddle.net/79epsrmw/. However, the issue arises when targeting the item1 sub-menu in VS Code even after assigning a unique id. var app = new Vue({ el: '#app', data: { menuItems: [ ...

Steps for converting a Calendar into a JSON format

I am working on developing a REST application like the one shown below: @XmlRootElement @Entity @Table(name = "tb_verarq") public class Verificacao implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

Struggling to send a POST request using the Fetch API? The provided examples may not be effective

I am encountering an issue with sending a post request to the server. The request.POST on the server seems to be empty for some unknown reason. Below are examples of the code: Front-end JavaScript: let weekends = [] await fetch('{% url "get_ ...

Exception thrown when file is not found in AngularJS routeParams

Here is an example I created var myApp = angular.module('MySampleApp', ['ngRoute']); myApp.controller('SampleCtrl', ['$scope', '$routeParams', function($scope, $routeParams) { $scope.employee = { ...

What could be causing my HTML checkbox to not function properly on mobile devices?

Having an issue with my website where users are unable to click the checkbox on mobile devices. Despite searching online, I have not been able to find a solution to this problem. .jg-c-register_label { display: grid; } .jg-c-register_label-text { c ...

Leveraging the Axios content delivery network for Vue Template presentation

I am looking to extract JSON data using the Axios library. By utilizing my {{ id }}, I aim to target a specific parameter in the request. Furthermore, I have an external script file for this purpose. const Home = { template: ` <div class="us ...

Colorbox scalePhotos function malfunctioning

The scalePhotos option in Colorbox does not seem to be working correctly for me. I have tried various methods to set it, including initializing Colorbox using the following code snippet right before the closing </body> tag in my HTML: jQuery('a ...

What is the best way to deactivate a button when not all inputs require filling?

I need to make a change in my form where I want to disable a button, but not all the inputs are mandatory. Even though I have specified which inputs need to be filled in the code, I still have to fill all the inputs in the form. How can I modify this? $ ...

Tips on how to modify a nested document in mongoose database model

Recently, I started developing a kanban task management application. While I have successfully implemented creating and deleting tasks, I am facing challenges when it comes to updating nested task objects. Despite my efforts in exploring the documentation, ...

Searching for specific tags using PHP and JavaScript in MySQL: effective strategies to find what you're looking

What is the most efficient way to search for an item based on user-defined tags? Consider the following data: item | param ----------------- 1 | a 1 | b 1 | c 2 | b 2 | c 2 | d 3 | c 3 | d 3 ...

Optimizing Performance: AngularJS and Rails - Deciding Between Integration or Separation for Improved js and css Asset Pipelines

Currently, I am in the process of building an AngularJS frontend and Rails API backend web application. After deploying it onto an Amazon medium EC2 instance, I noticed that the performance was not as impressive as I had hoped, especially when it came to t ...

How to generate PDF downloads with PHP using FPDF

I am attempting to create a PDF using FPDF in PHP. Here is my AJAX call: form = $('#caw_auto_form'); validator = form.validate(); data = form.serializeObject(); valid = validator.form(); //alert("here"); ajax('pos/pos_api.php',data,fun ...

Error Encountered in AngularJS: Request Unexpected (No Additional Requests Anticipated)

In my AngularJS project, I'm facing a challenge in writing unit tests to verify that executing a promise's then function changes the location.url. The function login within the AuthenticationService service is responsible for this behavior. Belo ...

Save JavaScript console output to a log file using Firefox

We are currently utilizing a web application that operates in kiosk mode using Firefox with the RKiosk extension. A potential issue we've encountered is a rare JavaScript error within the system. Unfortunately, due to the inability to access the JavaS ...

A step-by-step guide on integrating dynamic components in vue-class-component

After successfully using vue-class-component in my project, I decided to introduce a new component for production only: import store from '../store/Index' let storeTmp = process.env.NODE_ENV === 'production' ? store : null @Component({ ...

Guide on importing table information into an array using jQuery

I am facing an issue where I want to extract values from a dynamically generated table and then send those values in an AJAX call. The problem is that even though I am able to increase the number of rows in the table dynamically, when I try to capture the ...