Pressing the enter key in an AngularJS form does not trigger submission

Having trouble with a login form that won't submit when the user presses enter. While the form works fine when the "Login" button is clicked, hitting enter doesn't trigger submission and leads to some unexpected behavior:

  • The ng-submit associated function is not executed
  • The error message (login failed) disappears and isn't displayed again after hitting enter

This is the markup in question:

<form ng-submit="login()" class="login-form">
    <div class="alert alert-danger" ng-class="{ 'display-hide': !showError }">
        <button class="close" data-close="alert"></button>
            <span> Login failed </span>
    </div>
    <div class="form-group">
        <label class="control-label visible-ie8 visible-ie9">Username</label>
        <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" ng-model="username"/>
    </div>
    <div class="form-group">
        <label class="control-label visible-ie8 visible-ie9">Password</label>
        <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" ng-model="password"/>
    </div>
    <div class="form-actions">
        <button class="btn btn-success uppercase">Login</button>
    </div>
</form>

I've even tried replacing <button...> with <input type="submit"...> but had no success.

Here's how the controller with the login() function looks:

.controller('LoginCtrl', ['$rootScope', '$scope', ..., function LoginController ($rootScope, $scope, ...) {
    $scope.showError = false;

    $scope.login = function()
    {
        console.log("logging in");
        $http({
            url: $scope.apiEndpointLogin,
            method: 'POST',
            data: {'username': this.username, 'password': this.password}
        }).then(function(response) {
            $scope.showError = false;

            [...]
        }, function() {
            $scope.showError = true;
        });

    };
}]);

Running on angular v1.4.0 and using angular-ui-router v.0.2.15 for routing.

Any help would be greatly appreciated, thank you!

Answer №1

Insert this code snippet:

 <input type="submit" class="btn btn-success uppercase" value="Login" > 

in place of

 <button class="btn btn-success uppercase">Login</button>

When creating form submit buttons, ensure they have a type of "submit."

UPDATE CODE:

<form   class="login-form"  ng-submit="login()" >
    <div class="alert alert-danger" ng-class="{ 'display-hide': !showError }">
        <button class="close" data-close="alert"></button>
            <span> Login failed </span>
    </div>
    <div class="form-group">
        <label class="control-label visible-ie8 visible-ie9">Username</label>
        <input class="form-control form-control-solid placeholder-no-fix" type="text" autocomplete="off" placeholder="Username" name="username" ng-model="username"/>
    </div>
    <div class="form-group">
        <label class="control-label visible-ie8 visible-ie9">Password</label>
        <input class="form-control form-control-solid placeholder-no-fix" type="password" autocomplete="off" placeholder="Password" name="password" ng-model="password"/>
    </div>
    <div class="form-actions">
        <input  type="submit" class="btn btn-success uppercase"  >
    </div>

</form>

Ensure that your LoginCtrl is positioned above your form in the DOM structure.

UPDATE CODE :

Please refer to this Plunker for further details.

Answer №2

Try using <input type ="submit" /> instead of a Button

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I incorporate a second main app.js file in Node.js to improve the organization and cleanliness of my codebase?

Hello, I am currently using Node.js and the Express framework for my project. All of my server-side code is contained within my app.js file, which has become quite complex with almost 250 lines of code. Now, I need to add authentication functionality to my ...

Navigating in Angular is easy when you understand how to use special characters such as

In order to set a unique path in AngularJS routing, I am looking for the following features: An optional parameter The ability to accept values of a relative path Here are some examples of the parameter values I need to work with: /ABC /ABC/123 /ABC/12 ...

Encountering a "Element is not defined" error in Nuxt when trying to render Editor.js and receiving

I've been working on creating an editor using Editor.js within my Nuxt project, but it seems like the editor isn't initializing properly when I render the page. import EditorJS from '@editorjs/editorjs'; interface IEditor { editor: E ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Is the parameter rejecting the use of orderBy for 'startTime'?

Hey there! I'm currently working on an AngularJS project in TypeScript that involves integrating Google API to fetch Google Calendar events. The syntax for making a call is specified in the documentation available at: https://developers.google.com/goo ...

Steps to position images and text side by side in a grid layout

Trying to create a grid layout with profile images and text aligned next to each other, but struggling with CSS. If anyone could provide some guidance, that would be greatly appreciated! Here is the HTML code snippet: <div class="col-sm-3" ...

Trouble with linkage in jQuery for AJAX requests in an external .js document

My asp.net application has a master file that includes the jquery.js file. On another page that uses this master page, I have my own jquery code. I attempted to move this code to an external file and then include it in my .aspx file. While most functions ...

Issue with Next.js's notFound() function not properly setting the 404 HTTP Header

Our decision to use Nextjs was primarily driven by the need for SSR and SEO optimization. We rely on an external REST API to fetch data on the front end, but we face challenges when trying to pre-render certain pages and display a proper 404 Not Found head ...

Executing a function in ExpressJS at regular intervals of 24 hours

Can someone share the most effective method to schedule an automated task every 24 hours in ExpressJS? I have thoroughly researched possible solutions but haven't found any option other than using an infinite loop. Is there only one way to achieve th ...

Create dynamic and interactive content by embedding text within SVG shapes using the powerful D

How can I write text into an SVG shape created with d3.js and limit it to stay inside the shape similar to this example http://bl.ocks.org/mbostock/4063582? I attempted to use a clipPath following the example provided. However, when inspecting with firebu ...

The Angular CLI encountered a 404 Not Found error while attempting to load the symbol-observable at http://localhost:4200

Issue encountered after upgrading angular cli to beta 9: Failed to load resource: the server responded with a status of 404 (Not Found) zone.js:461 Unhandled Promise rejection: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:4200/symb ...

Merging the `on('click')` event with `$(this)`

Hello everyone, this is my first time posting here. I have a question regarding the possibility of achieving a specific functionality. I would like to attach click events to a series of anchor links and then use the $.get() method to reload some icons. T ...

Conceal an element if the angular attribute does not contain any value

Currently, I am facing an issue with an image element in my project. The path for this image is being fetched from an attribute present on my angular object. However, if this imagePath attribute is empty, a broken image is displayed. I want to avoid rend ...

Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test. caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true) driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps) drive ...

How can I resolve the issue of shadow.static in Three.js causing shadows to shift when the shadow.bias is adjusted? Suggestions on

So I've got a scene with some nice shadows being cast by a light, but there's this pesky static issue with the shadow. Check it out: https://i.sstatic.net/k3XIe.jpg When I try to fix it with a simple tweak like light.shadow.bias = -0.005;: htt ...

A method that sorts an array of objects based on their properties

I am currently working with two specific objects: clinics: [ { id: 1, name: 'New Hampshire Veterinarian Clinic', plans: [ 'handle123', 'handle567', ] }, { ...

Determining the visibility of an element on a webpage using JavaScript and Puppeteer

I've created a framework that scans websites hosted on our servers to ensure they comply with our policies. If any prohibited content is found, we capture a screenshot along with other relevant details. However, taking a screenshot may not be possibl ...

Can someone explain to me how this AngularJS factory example functions? I have some uncertainty

As a beginner in AngularJS, I am currently studying it through a tutorial and have some questions regarding the use of the factory in Angular. From what I understand, a factory is a pattern that creates objects on request. In the example provided, we see ...

Running a <script> tag with an external src attribute in a dynamic manner through the use of eval

Currently, I am utilizing the Genius API to fetch lyrics for a particular song and then embed them within an HTML <div> tag. My interaction with this API is through PHP, employing an AJAX GET request. Upon a successful AJAX request, the following HT ...

Retrieve the prior position using the AngularJS ui-router

Utilizing fromState and fromParams within the $stateChangeSuccess event allows us to access all details regarding the previous location. This concept is elaborated in the following discussion: Angular - ui-router get previous state $rootScope.$on('$s ...