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

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

Displaying the structure of a MongoDB database using Express and Angular in a tabular format

I am looking to present the data from MongoDB in a table format using HTML along with Node.js, Express.js, and Angular.js. Currently, my approach is as follows: route.js app.get('/superhero', function(req, res) { superhero.superhero_list(r ...

Assign an id attribute in KineticJS once the ajax call is successful

I have implemented KineticJS into my MVC application. To retrieve data from the database, I am utilizing ajax calls to web services in the API controller. One of the APIs returns an id that I want to assign to the current Kinetic.Group id attribute upon s ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

Steps to dynamically set the value of an input type="time" using JavaScript

Despite the repetitive nature of these questions, I have yet to find a solution to my specific query. Any help would be greatly appreciated. Thank you in advance. The HTML code is as follows: var start="10:30 PM"; $scope.edit={} frtime=start.split("PM ...

Guide on accessing a modal component in Angular?

I have an Edit Button on my component called SearchComponent. When the user clicks this button, it currently redirects them to another component named EditFormComponent using navigateByUrl('url-link'). However, I would like to enhance the user ex ...

Responsive design involves ensuring that web elements such as divs are properly aligned

I am currently working on aligning 2 divs in a specific way that is responsive. I would like the right div to stack on top of the left div when the screen width reaches a certain point, as opposed to them both taking up 50% of the container's width. ...

Exploring the concept of utilizing named arguments within Express.js routing

I've searched extensively, but can't seem to find any information on this topic. My goal is to create requests like the following: url/list/message=hello?id=1234 Despite my efforts, I have not come across any resources on how to achieve this us ...

Unable to extract all advertisements from Facebook Marketplace

https://i.stack.imgur.com/xEhsS.jpg I'm currently attempting to scrape listings from Facebook marketplace, however, only the first listing is being scraped. Does anyone have any suggestions on how I can scrape the entire list of listings? CODE (async ...

Using Asynchronous JavaScript and XML (AJAX) to make calls to a web service

My program is showing an internal server error var parameters = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3. ...

Discrepancy in functionality between Android and JavaScript Parse API

Using the open source version of Parse Server as a back end, my Android application saves objects to the server's DB in the form of key-value pairs encoded as JSON. However, when trying to retrieve the same object from an Ionic 2 app using the JS Pars ...

Personalizing Web Push Alerts (Google Chrome)

I successfully implemented a web push notification for Google Chrome using Google Project and Service Worker. One thing I'm curious about is how to customize or style the push notification. The plain message box doesn't quite cut it for me – I ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

Next.js does not support Video.js functionality when using server side rendering

I'm struggling to set up video.js in my next.js project and encountering issues. When the player is loading, it initially appears black and then disappears abruptly. A warning message in the console reads: "video.es.js?31bb:228 VIDEOJS: WARN: T ...

The individual is currently tracking his own movements

When developing a function to handle user following and unfollowing, I encountered an issue where the code checking if a user can follow themselves was not functioning as expected. Despite implementing an if statement to prevent self-following, users were ...

Looking to scan through a directory of .html files in Node.js to find specific element attributes?

Imagine trying to tackle this task - it's like reaching for a needle in a haystack. Picture a folder containing a static website, complete with images, stylesheets, and HTML files. My Node application needs to dive into this folder and extract only th ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Integrate these scripts for seamless functionality: JavaScript/AJAX and PHP

Currently, I am in the process of learning all the languages involved here and facing a challenge while trying to merge two scripts to perform a single task. The goal is to select a branch from a form option list, transmit that value from the option to a ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

ways to make a list element inaccessible by using either Javascript or jQuery

When the user clicks on my eraser, I want the color to be hidden or not display its dropdown elements. I attempted this with the following code snippet. $('#chooseEraser').mousedown(function(e){ curTool = "eraser"; checkEraser ...