Prevent form submission on enter key

后端 未结 15 1340
夕颜
夕颜 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:39

    I came across this issue. Yes, you would need to remove all type='submit' from your page, and make sure any other buttons have type="button" but then the challenge is still being able to use normal validation submission.

    I created a directive that triggers form submission + form states for validation. Replacing:

    with

    Directive:

    export default /*@ngInject*/ function submitButton($log) {
    return ({
        require: '^form',
        link: link,
        restrict: 'A'
    });
    
    function link(scope, element, attributes, formCtrl) {
    
        element.on('click', clickHandler);
    
        function clickHandler() {
            formCtrl.$setDirty(true);
            formCtrl.$setSubmitted(true);
            angular.element(element[0].form).triggerHandler('submit');
            $log.info('Form Submitted');
        }
    
    }
    

    You can still hit ENTER to submit when focused on your submit-button, better for UX and Accessibility I think.

提交回复
热议问题