Question

I have a multi-step form with 5 steps. I'd like the user to be able to use the enter key to submit each of the sub forms to trigger validation and moving to the next sub form on success. I can't find a way to do this. I was thinking perhaps I could add ng-keydown events to each of the sub forms (or a custom directive binding to onkeydown) and watch for the enter key keyCode.

Does anybody have experience with getting this to work in Angular? How would you add this functionality?

Here's a brief HTML sample of the sub-forms. Assume the "Next Step" button is triggering $scope.nextStep() within an angular controller and that subsequently performs validation to determine if the user can move to the next step or if a validation error is displayed.

<form>
    <div ng-form="step1"></div>
    <div ng-form="step2"></div>
    <div ng-form="step3"></div>
    <div ng-form="step4"></div>
    <div ng-form="step5"></div>

    <button type="button" class="btn" ng-click="nextStep()">Next Step</button>
</form>

For those of you reading and looking for more info on the answer

I track the form step inside of my controller's $scope.current_step. Using that, I'm able to use $scope[$scope.current_step] to reference the current form. With @Vova's accepted answer below, I would do something similar to the following:

$scope.myFunc = function(event) {
    if (!$scope.isFormValid()) {
        return false;
    } 

    // trigger next step (which handles it's own validation)
    $scope.nextStep();
};

$scope.isFormValid = function() {
    // check if the current form is invalid
    if ($scope[$scope.current_step].$pristine
        || $scope[$scope.current_step].$invalid
    ) {
        return false;
    }

    return true;
};
Was it helpful?

Solution

using ng-keyup directive set function that can get the Enter (13) key event, and fire up your validation/stepForward function.

other solution, add angular-ui, and do something like this:

<form ui-keypress="{13:'myFunc($event)'}">
  ... input fields ...
</form>

more solutions: Submit form on pressing Enter with AngularJS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top