Matoy
Matoy

Reputation: 1818

angular's ng-submit() directive does not submit while pressing enter on one of text fields

I've constructed a simple form using angular. I want that once the user enter some value and then press enter - the ng-click function (in this case updateMsg({name: name,room: room})) will be run.

However, this code does not work like that.. the function run only after pressing the button (not like I want - enter keyboard value, then enter..)

Code is below...

help please?

Thanks

<body>
    <div class="Member">
        <h1>Sign In</h1>
        <form name="myForm" ng-submit="updateMsg({name: name,room: room})">
            Please enter your details:
            <br>
            Name: <input name="name" ng-model="name" autocomplete="off">
            <br>
            Room: <input name="room" ng-model="room" autocomplete="off">
            <br>
            <button type="button" ng-click="updateMsg({name: name,room: room})">

            Enter
            </button>
        </form>
    </div>
</body>

Upvotes: 0

Views: 49

Answers (3)

Marios Fakiolas
Marios Fakiolas

Reputation: 1545

You should not use ng-click and ng-submit directives together. Add type="submit" to your button like this:

<button type="submit">Enter</button>

and keep only ng-submit:

    <form name="myForm" ng-submit="updateMsg({name: name,room: room})">
        Please enter your details:
        <br> Name:
        <input name="name" ng-model="name" autocomplete="off">
        <br> Room:
        <input name="room" ng-model="room" autocomplete="off">
        <br>
        <button type="submit">Enter</button>
    </form>

Also there is no point in doing ng-submit="updateMsg({name: name,room: room})" to pass your updated data like that. Since you are using ng-model you are ready to go. You can declare your scope vars initially in the controller and when the form gets submitted you can use them right away. Because of dual-binding your vars will be already updated:

angular
.module('myApp', [])
.controller('MemberController', ['$scope', function($scope) {
    $scope.name = '';
    $scope.room = '';
    $scope.updateMsg = function() {
        // use updated $scope.name in here
        // use updated $scope.room too
    }
}]);

A small plunker to help you some more.

Upvotes: 1

Anirudha
Anirudha

Reputation: 32787

I think the button should have type=submit instead.

<button type="submit">

instead of

<button type="button" ng-click="updateMsg({name: name,room: room})">Enter</button>

Upvotes: 1

Mike Hohne
Mike Hohne

Reputation: 472

Are you calling a event.preventDefault() method so the form doesn't submit by default? Maybe share the code where you're creating the updateMsg({name: name,room: room}).

Upvotes: 0

Related Questions