Rahul Khatri Rahul Khatri - 4 months ago 31
Javascript Question

How do I prevent form submission in Angularjs if I am submitting the form using enter key?

I have applied validation to my form (It has only two fields) but don't know how to prevent it from submitting,Current flow is: After pressing enter key the student's name and marks are added on localstorage and are displayed on the screen from there but I am unable to prevent empty data from submitting.

These are my js 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);

};


This is the html part:

<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

Supposing that your fields are correctly validating, to prevent the submit you could use ngDisabled directive, as below:

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

EDIT: Since the OP provided the full code I was able to give the correct answer, that is:

Change the check to:

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

Snippet working 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>

Tips:

  1. The ngModel $scope.marks is already a number, you don't need to to do any parse, so you can have 'Marks': $scope.marks.

  2. The check of pass can simply reduced to: 'pass': $scope.marks > 65