Prevent form submission on enter key

后端 未结 15 1139
夕颜
夕颜 2020-12-05 06:24

How can I prevent the enter key from submitting the form in angular?

Is there a way to catch the 13 key and disable it or set the form as invalid unless submitting f

相关标签:
15条回答
  • 2020-12-05 06:45

    This is my weird but quick and simple solution without any directives.

    HTML:

      <form ng-submit='submitForm()'>
        <input type='text'>
        <button type='submit' ng-mousedown='doSubmit=true'>submit</button>
      </form>
    

    Controller:

      $scope.submitForm = function() {
        if (!$scope.doSubmit) {
            return;
        }
        $scope.doSubmit = false;
        console.log('execute some actions');
      }
    
    0 讨论(0)
  • 2020-12-05 06:47

    A form is submitted when the enter key is clicked while a control within the form has focus. If you register a listener using ng-submit you can intercept this and use prevent defaults to stop the default process (i.e. submitting the form). Have a look at th

    0 讨论(0)
  • 2020-12-05 06:49

    If you are attempting to prevent the form from being submitted on just a single element, you can add the following ng-keypress handler (this is for Angular 1.x):

    <input type="text" name="myField" ng-keypress="keyPressHandler($event)"/>
    

    With the following implementation for keyPressHandler:

    $scope.keyPressHandler = function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            e.stopPropagation();
    
            // Perform your custom logic here if any
        }
    }
    
    0 讨论(0)
  • 2020-12-05 06:50

    Try setting a variable when you click the submit button and checking that it has been set in the form submit.

    $scope.click = function () {
        $scope.clicked = true;
        $scope.submit();
    };
    
    $scope.submit = function () {
        if ($scope.clicked) {
            ... submit
        } else {
            ... prevent defaults
        }
         $scope.clicked = false;
    };
    

    See jsfiddle

    0 讨论(0)
  • 2020-12-05 06:51

    Check this:

    if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit

    Thus if your form has 2+ input fields, you could use something like <span ng-click="submit()">Sumbit</span> to prevent key-trigger of enter key in those input fields.

    0 讨论(0)
  • 2020-12-05 06:53

    Other users have already written that [button type="submit"] will cause this trouble. PLEASE NOTE: buttons WITHOUT any type="..." declaration are "submit" by default! So make sure you always use type="button".

    0 讨论(0)
提交回复
热议问题