Bye bye validation for cancel button in AngularJS

I am striving to implement a specific feature in my Angular application. I want to have editable form inputs, where a user can view their first name fetched from the server and then switch to an edit mode by clicking a button. The edit button transforms into save and cancel buttons during editing. To display errors, I utilize the angular-bootstrap-show-errors component.

However, I encountered an issue where if a validation rule is not met while editing and I click on the cancel button, the form attempts to show the error before reverting back to its initial state. Here is the code snippet of my view:

<!--First name edits-->
<div class="row">
    <form name="firstNameEditForm" role="form" novalidate>
        <div class="col-xs-3">
            <p class="text-right">First Name:</p>
        </div>
        <div class="col-xs-6" ng-if="model.beforeFirstNameEdit">
            <p class="text-success">
                {{accountData.firstname || "Loading..."}}
            </p>
        </div>

        <div class="col-xs-6" ng-if="!model.beforeFirstNameEdit">
            <div class="form-group" show-errors>
                <input name="firstName" ng-model="accountData.firstname" class="form-control" placeholder="First Name" type="text" required minlength=2 auto-focus />
                <small class="help-block" ng-if="firstNameEditForm.firstName.$error.required">At least 2 characters required</small>
                <small class="help-block" ng-if="firstNameEditForm.firstName.$error.minlength">At least 2 characters required</small>
            </div>
        </div>

        <div class="col-xs-3" ng-if="model.beforeFirstNameEdit">
            <button type="button" class="btn btn-warning btn-xs" ng-click="editFirstName()">Edit</button>
        </div>

        <div class="col-xs-3" ng-if="!model.beforeFirstNameEdit">
            <button type="button" class="btn btn-success btn-xs" ng-click="update(accountData.firstname)">Save</button>
            <button type="button" class="btn btn-danger btn-xs" ng-click="cancelFirstNameEdit()">Cancel</button>
        </div>
    </form>
</div><!--First name edits-->

As for the controller:

$scope.preFirstNameEditModel = {};
$scope.editFirstName = function() {
    // Copy preedited data locally
    $scope.model.beforeFirstNameEdit = false; 
    $scope.preFirstNameEditModel = angular.copy($scope.accountData.firstname);
}

$scope.cancelFirstNameEdit = function(){
    $scope.model.beforeFirstNameEdit = true; 
    $scope.accountData.firstname = angular.copy($scope.preFirstNameEditModel);
};

I am seeking advice on how to prevent validation from triggering when clicking the cancel button. I have tried changing the button type to "button", but it has not resolved the issue.

Answer №1

When the fields lose focus, validation is triggered which generates a validation message. To prevent this behavior, you can use

ng-show="submitted && firstNameEditForm.firstName.$error.required"
and
ng-show="submitted && firstNameEditForm.firstName.$error.minlength"
. This will ensure that the message only appears when the form is submitted.

Additionally, make sure to change the type of the update button to submit.

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

Tips for effectively utilizing the Ngrx navigation function

While exploring NgRx, I stumbled upon navigation. According to the documentation, it seems like this effect should trigger when the component loads. However, I'm facing an issue where this effect is not getting triggered. Other effects that I've ...

discord.js: Bot keeps sending duplicate embeds

I recently set up my discord bot to respond with a message when I enter a specific command, but I've run into an issue where it's sending the same embed twice. I've tried troubleshooting, but so far I haven't been able to pinpoint the c ...

Generate HTML on the fly using Node variables

Utilizing Node.js with Express as the server, I have implemented a feature where users can upload .CSV files containing data. This data is then parsed and stored in a main array made up of arrays, with each line representing one array element. Currently, I ...

Challenges arise when adjusting frame size for mobile and desktop devices

I am trying to achieve an auto-resize feature for my frame's height when the screen width is smaller than a certain value. I want it to behave like Sketchfab, as demonstrated in this video: http://www.youtube.com/watch?v=_y5ckVFGHKU&feature=youtu. ...

Implement a Bootstrap accordion onto a webpage seamlessly alongside an outdated jQuery version to avoid any conflicts

My bootstrap accordion is not functioning properly, the animation seems to be broken. How can I fix it? I suspect that it might be due to using an outdated version of jQuery or because the theme developers implemented a custom solution. The end result is ...

Error message: "Unable to locate module for split-pane-react in Jest"

Attempting to run Jest tests on my component with [email protected] in a Next.js project using typescript. Encountering the following error: Cannot locate module 'split-pane-react' from 'my component path' when running the test ca ...

Exploring cookie evaluation in AngularJS routes and templates

I am in the process of implementing a login system using cookies to ensure that a user stays logged in even after leaving the application. While I have successfully set the cookie, I am unsure of how to utilize it to restrict access to the login screen for ...

Converting Geometry into BufferGeometry

From my understanding, Geometry contains a javascript object structure of the vertices and faces, while BufferGeometry stores raw WebGL data using Float32Arrays, etc. Is there a method to convert regular Geometry into BufferGeometry, which is more memory ...

Retrieve a subset of fields from a collection of nested documents

My document looks like this: { "_id" : "2", "account" : "1234", "positions" : { "APPL" : { "quantity" : "13", "direction" : "long" }, "GOOG" : { "quantity" : "24", "direction" : "long" } } } I want to retrieve the entire positions object, but only ...

Troubleshooting: Jquery form submission function not functioning as expected

My jQuery code is working fine with functions like hide(), but I am facing an issue with submit() function. When I try to submit the form, nothing happens! I would really appreciate it if someone could help me with this. Here is my form: <form class ...

Extract a portion of a phrase from a specified component

I've been using the wpdiscuz plugin for WordPress and I'm looking to remove a specific part of the content within the .wc-comment-title element. Specifically, I want to use jQuery or JavaScript to delete a portion of a sentence within a paragraph ...

What is the most effective way to declare a variable in TypeScript when assigning it within a class?

Is there a more efficient way to define the class variable accountHandler without using any? main.ts private accountHandler: any= {}; private requestLOB: string[] = []; constructor() { if (process.env.ENABLEBackendSwitch === "true&q ...

Is there a way to prompt Vue Router to refresh my page while attempting to navigate within the present location?

I currently have my project structured in the following way: Views Home.vue Classroom.vue App.vue Within the Home.vue file, I display the content and a login form. Essentially, users must submit their login information, and if correct, the isAuth vari ...

Utilizing JavaScript: Storing the output of functions in variables

Currently in the process of learning JavaScript and aiming to grasp this concept. Analyzed the following code snippet: function multiNum(x, y){ return x * y; } var num = multiNum(3, 4); document.write(num); Decided to try it out on my own, here's ...

jQuery disrupts the functionality of other scripts

Let me start by saying that I have very little knowledge about scripting and HTML. Recently, I came across the following code: <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> < ...

Failed to validate user profile because of an InternalOAuthError error while using passport-facebook-token to verify the token

In my iOS application, I am utilizing the Facebook API for user login and receiving an access token in return. Now, I need to use this token to verify a user on my backend server. For this purpose, I have implemented the passport-facebook-token strategy w ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

Developing a Jquery solution for creating radio buttons layout

Looking to create a radio button functionality within different groups using multiple select. For Group A: If the user selects A1, then it should automatically deselect A2 and A3. If the user selects A2, then it should automatically deselect A1 and A3. I ...

Scroll down 1 page using Javascript and Jquery

Hey there! I'm looking to create a website where a small scroll on the mouse wheel will take the site to the next anchor. It's kind of hard to explain, but one good example is the Tesla Model 3 website on the US site here. Does anyone have any t ...

Explore the differences between user input and JavaScript

There seems to be an issue with the second output result. var compareNumber = 3; // Code will be tested with: 3, 8, 42 var userNumber = '3'; // Code will be tested with: '3' 8, 'Hi' /* Enter your answer here*/ if (userNum ...