What is the best way to stop form submission in AngularJS when submitting the form by pressing the enter key?

I have implemented validation on my form (which consists of only two fields) but I am struggling to figure out how to prevent it from being submitted with empty data. The current flow is as follows: Upon pressing the enter key, the student's name and marks are added to local storage and displayed on the screen. However, I need to find a way to prevent submission of empty data.

Below are my JavaScript functions:

$scope.searchEnter = function() {
    if (event.which == 13 && $scope.student != "") {
        $scope.addStudent();
    }
};
$scope.addStudent = function() {
    if ($scope.marks > 65) {
        var pass = true;
    } else {
        pass = false;
    }
    $scope.students.push({ 'studentName': $scope.student, 'Marks': parseInt($scope.marks), 'pass': pass });
    $scope.student = '';
    $scope.marks = '';
    localStorage['studentsList'] = JSON.stringify($scope.students);

};

Here is the HTML portion:

 <div class="row">
        <div class="col-xs-12">
            <form class="form-horizontal" novalidate name="studentForm" >
                <div class="form-group">
                    <label class="col-sm-2 control-label" for="student_name">Student's Name</label>
                    <div class="col-sm-5">
                    <input ng-model="student" ng-keyup="searchEnter()" type="text" class="form-control" id="student_name" ng-required="true" name="stdname">
                        <div ng-show="studentForm.stdname.$touched && studentForm.stdname.$invalid">
                            <small style="color:red; display:block;">Enter a valid name </small>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-sm-2 control-label" for="student_marks">Marks obtained</label>
                    <div class="col-sm-5">
                    <input ng-model="marks" ng-keyup="searchEnter()" type="number" class="form-control" id="student_marks" ng-required="true">Press ENTER to insert student's data in the table.</div>
                </div>
            </form>
        </div>
    </div>

Answer №1

Assuming that all your fields are validating correctly, you can prevent the form submission by utilizing the ngDisabled directive as shown below:

<button type="submit" ng-disabled="form.$invalid">Submit</button>

UPDATE: With access to the complete code provided by the OP, I was able to provide the accurate solution which is:

Modify the condition to:

if (event.which == 13 && $scope.student && $scope.marks) {

Code snippet based on your code:

(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  MainCtrl.$inject = ['$scope'];
  
  function MainCtrl($scope) {
    $scope.students = [];

    $scope.searchEnter = function() {
      if (event.which == 13 && $scope.student && $scope.marks) {
        $scope.addStudent();
      }
    };

    $scope.addStudent = function() {
      console.log('addStudent called');
      $scope.students.push({
        'studentName': $scope.student,
        'Marks': $scope.marks,
        'pass': $scope.marks > 65
      });
      $scope.student = '';
      $scope.marks = '';
      localStorage['studentsList'] = JSON.stringify($scope.students);
    };
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
</head>

<body ng-controller="MainCtrl">
  <div class="row">
    <div class="col-xs-12">
      <form class="form-horizontal" novalidate name="studentForm">
        <div class="form-group">
          <label class="col-sm-2 control-label" for="student_name">Student's Name</label>
          <div class="col-sm-5">
            <input ng-model="student" ng-keyup="searchEnter()" type="text" class="form-control" id="student_name" ng-required="true" name="stdname">
            <div ng-show="studentForm.stdname.$touched && studentForm.stdname.$invalid">
              <small style="color:red; display:block;">Enter a valid name </small>
            </div>
          </div>
        </div>

        <div class="form-group">
          <label class="col-sm-2 control-label" for="student_marks">Marks obtained</label>
          <div class="col-sm-5">
            <input ng-model="marks" ng-keyup="searchEnter()" type="number" class="form-control" id="student_marks" ng-required="true">Press ENTER to insert student's data in the table.</div>
        </div>
      </form>
    </div>
  </div>
</body>

</html>

Helpful hints:

  1. The ngModel $scope.marks is already a number so there's no need for any additional parse, simply use 'Marks': $scope.marks.

  2. The check for pass can be simplified to: 'pass': $scope.marks > 65

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

Issues with the ES version affecting back4app cloud code functions

Utilizing back4app as my backend service for deploying my React Native and JS app, I am currently experimenting with the 'Cloud Code Functions' feature. Being new to back4app, I encountered an issue when following their guide. I received this er ...

The null object does not have a property addEvenListener and therefore cannot be

My goal is to develop a simple single-page application without using any frameworks, focusing on providing users with tutorials on specific subjects. I am encountering an issue with the javascript code for my page, receiving the following error: Uncaug ...

Ways to update the div's appearance depending on the current website's domain

There is a piece of code that is shared between two websites, referred to as www.firstsite.com and www.secondsite.com The goal is to conceal a specific div only when the user is on secondsite. The access to the HTML is limited, but there is an option to ...

Managing authentication tokens in next.js

I'm currently working on a next.js app that requires authorization for certain functionalities. In the past with CRA, I would store the token in a config.js file and easily import, use, and update it throughout my application. Here is an example of ho ...

Having trouble with the dropdown menu in Bootstrap?

I'm having trouble creating a responsive dropdown menu. When I click on the dropdown items, nothing happens. Here's the code: <div class="navbar-header"> <button type="button" class="navbar-toggel" data-toggel="collapse" data-target="#m ...

Need to swiftly modify values of css attributes?

Here is a snippet of the code I am working with: <div></div> <button> Go </button> div { width: 50px; height: 50px; border: 1px solid #ccc; } var bgs = ['red', 'blue', 'yellow', 'green&apo ...

Accessing a webpage solely by logging in prevents unauthorized access

My login page currently redirects to a page named gallery.html upon successful login. However, I have noticed that entering /gallery.html in the URL also directly accesses the secure page without logging in. Can anyone suggest an effective way to impleme ...

Error: EPERM -4048 - the system is unable to perform the operation specified

Every time I attempt to install a package using npm install, I encounter an error message (usually referring to a different path). I have attempted running npm cache clean, restarting my computer, and checking for any processes that may be interfering with ...

Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close. <div v-for="(btn, index) in dataArray"> ...

The error message "this.props.navigation" is not defined and cannot be evaluated as an object

Recently, I encountered an issue with my navigation system. Within my application, there are 3 screens or components that I navigate between using react-navigation. The first screen prompts the user to enter their mobile phone number and password, which is ...

Retrieve the node-postgres result and store it in a separate object beyond the callback function

Currently, I am in the process of converting a data profiling script originally written in Python to JavaScript while following the Wes Bos beginner Javascript Course. This script is designed to take database connection details and a specified target tabl ...

Vue element fails to appear on the screen

As a newcomer to Vue.js and web development in general, I decided to dive into the vuejs guide. Something puzzled me - when creating a vue component using Vue.component(NameOfComponent, {...}) and inserting it into my HTML as <NameOfComponent></ ...

Enhancing performance by dynamically updating DOM elements when they come into view during scrolling

Currently, I am in search of an efficient algorithm to dynamically load background-images for a group of <li>'s but I am encountering some efficiency issues. The code I am using at the moment is as follows: function elementInView($elem, vps, vp ...

Ways to determine if JavaScript array objects overlap

I am working with an array of objects that contain start and end range values. var ranges = [{ start: 1, end: 5 }] My goal is to add a new object to the array without any overlapping with the existing ranges, { start: 6, end: 10 } I need ...

Vue: The enigmatic world of ghost properties?

During my project work, I encountered the following code snippet: Main component - <ParameterModal>: <template> <modal-wrapper props="..."> <!-- ... other similar templates are present... --> <template v-else-if="moda ...

Encountering a Problem Combining Angular Js with Dot Net Nuke 7

After creating a custom user-defined controller and adding a module in dnn7 (with resources for the custom controller), I created a page in dnn7 to access my newly created Module. However, when I tried accessing it, only my HTML Page was displayed. This me ...

Passing image source from parent component to child component in Vue.js

I encountered an issue where I stored the image file name in a variable within the parent component and passed it to the child component using props. However, despite this setup, the child element is not displaying the image as expected. Here is the data ...

What could be causing the remaining part of the template to not render when using an Angular directive?

After adding my custom directive to a template on an existing page, I noticed that only the directive was rendering and the rest of the template was not showing up as expected. Even though the controller seemed to have executed based on console logs and B ...

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

submit a new entry to add a record to the database

Hey there, I recently started learning PHP and JS and I'm trying to insert a row into a WordPress database table. I need to get the information needed for insertion from another table, but I'm facing an issue with the PHP file as it's not in ...