Reset the form upon submission in AngularJS

Hey, I'm looking to reset the form values after a successful submission. How can I achieve this?

<div ng-controller="employeelistController as listControl">
        <div class="container form-group" ng-controller="addEmployee as addemp">
            <form name="frmEmployee" ng-submit="Add(addemp.employee) && frmEmpbloyee.$valid">
                <div class="col-lg-4 ctrmain">
                    <div class="row">
                        <div class="col-lg-6">
                            <strong>Employee No</strong>
                        </div>
                        <div class="col-lg-6">
                            <input type="number" id="txtEmpId" ng-model="addemp.employee.employeeid" required class="form-control" />
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-6">
                            <strong>FirstName</strong>
                        </div>
                        <div class="col-lg-6">
                            <input type="text" id="txtfirstName" ng-model="addemp.employee.firstname" required class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6">
                            <strong>LastName</strong>
                        </div>
                        <div class="col-lg-6">
                            <input type="text" id="txtlastName" ng-model="addemp.employee.lastname" required class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6">
                            <strong>Department</strong>
                        </div>
                        <div class="col-lg-6">
                            <input type="text" id="txtDept" ng-model="addemp.employee.department" required class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-lg-6">
                            <strong>DOB</strong>
                        </div>
                        <div class="col-lg-6">
                            <input type="date" id="DTdob" ng-model="addemp.employee.dateofbirth" required class="form-control" />
                        </div>
                    </div>
                    <div class="row">
                        <input type="submit" id="btnSubmit" class="btn btn-primary value=" save" />
                    </div>
                </div>

Can someone suggest the most effective way to do this? I've tried various methods but need some guidance.

$scope.Add = function (emp,$scope) {

        this.EmployeeObject = angular.copy(emp);
        employee.push(this.EmployeeObject);
        $scope.emp = null;
    }

I'm still trying to figure out the best approach for this issue. Any help would be appreciated.

Answer №1

To begin with, there is no need for $scope to be included in the argument of the Add function.

  $scope.Add = function (emp) {     
    this.EmployeeObject = angular.copy(emp);
    employees.push(this.EmployeeObject);
    this.employee=null;
    $scope.$setPristine(true);
}

Answer №2

customize it with the demonstration

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope, $compile) {
  'use strict';

  
      $scope.employeeList = [];
    $scope.addEmployee = {};
    $scope.saveEmployee = function(){
      $scope.employeeList.push($scope.addemp);
      $scope.reset();
    };
    $scope.reset = function() {
      $scope.addemp = {};
      $scope.form.$setPristine();
    }
});
input.ng-invalid.ng-dirty {
          background-color: #FA787E;
        }
        input.ng-valid.ng-dirty {
          background-color: #78FA89;
        }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MainCtrl">
        <form name="form" id="form" novalidate ng-submit="saveEmp()">
            <div class="row">
        <div class="col-lg-6">
            <strong>Employee No</strong>
        </div>
        <div class="col-lg-6">
            <input type="number" id="txtEmpId" ng-model="addemp.employeeid" required class="form-control" />
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <strong>FirstName</strong>
        </div>
        <div class="col-lg-6">
            <input type="text" id="txtfirstName" ng-model="addemp.firstname" required class="form-control" />
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <strong>LastName</strong>
        </div>
        <div class="col-lg-6">
            <input type="text" id="txtlastName" ng-model="addemp.lastname" required class="form-control" />
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <strong>Department</strong>
        </div>
        <div class="col-lg-6">
            <input type="text" id="txtDept" ng-model="addemp.department" required class="form-control" />
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6">
            <strong>DOB</strong>
        </div>
        <div class="col-lg-6">
            <input type="date" id="DTdob" ng-model="addemp.dateofbirth" required class="form-control" />
        </div>
    </div>
    <div class="row">
        <button type="submit" ng-disabled="form.$invalid ">Submit</button>
        <button type="reset" ng-disabled="form.$pristine" ng-click="reset()">Reset</button>
    </div>
        </form>
        <p>form: {{addemp | json}}</p>
        <p>employeeList: {{employeeList | json}}</p>
        <p>Pristine: {{form.$pristine}}</p>
        <p> <pre>Errors: {{form.$error | json}}</pre>

        </p>
    </div></div>

$scope.Add = function (emp) {
                this.EmployeeObject = angular.copy(emp);
                employee.push(this.EmployeeObject);
                $scope.emp = {}; // initialize the form to empty object 
                $scope.frmEmployee.$setPristine(); // set it to as user has not interacted with the form.
            }

Answer №3

I successfully emptied the input field using the code provided below. For example, I cleared the FirstName input field.

HTML SECTION

<td ng-show="a">
 <input type="text" ng-model="e.FirstName" />
</td>

Controller SECTION

e.FirstName= "";

Answer №4

let application = angular.module('app', []);

application.controller('MainCtrl', function($scope, $compile) {
  'use strict';
function clearForm() {
document.getElementById("frmEmployee").reset();
}
$scope.Add = function (employeeRecord,$scope) {
        this.EmployeeProfile = angular.copy(employeeRecord);
        employees.push(this.EmployeeProfile);
        clearForm();
    }
});

Answer №5

Using a concise line of JavaScript, this code can reset form fields effortlessly.

document.getElementById('theForm').reset()

Simply insert this snippet at the conclusion of your controller function to reset the form upon submission.

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

Issue encountered with the style parameter in print-js when attempting to print from a Vue.js component

While browsing the print-js documentation, I came across a feature that allows us to pass style as a string to the printJS function. However, when attempting to apply this style, I encountered an error preventing the print action: The error I'm facin ...

Discover the power of positioning data labels in c3js!

Is there a way to adjust the position of labels above the data in a c3 bar chart? The official documentation explains how to modify the positions of labels on the x and y measurement axes by manipulating integers for y and x, but I couldn't find any i ...

"Unexpected behavior: Angular route parameters are found to be empty upon receiving the API

Seeking to extract parameters from the urlcallback received from an external authentication source, within my Angular project using angular-route/$routeProvider The API redirect is as follows: http://localhost:8080/dist/?somevar=someval&val2=someot ...

Adding a new row to an HTML table using JavaScript

In the code snippet below, I am facing an issue with adding a row to an HTML table and inserting it into a database. I have tried using JavaScript to add the row in order to avoid postback, but so far, I have been unsuccessful. Can someone assist me in t ...

Blazor combines the power of both C# and JavaScript by allowing them to be executed in a single

There is a button that triggers a JavaScript function: <button class="btn-orange btn" onclick="expand(this.closest('.profile'))">JavaScript</button> And there is another button that executes C# code and toggles ic ...

I am experiencing an issue where the position of the value in the returned response array keeps changing after an Ajax request is made. How can

I am currently using a script that sends an array of numbers through Ajax to a web server. These numbers are then used to query a database, and the corresponding values from the table are sent back. I then display these values in respective divs within my ...

Sending information back to the server without causing a postback, all while remaining unseen

I have a straightforward JavaScript function on my ASP.NET page that writes data to a hidden field. However, in order to retrieve this data the form needs to be submitted back to the server. The issue is that submitting the form causes the page to reload ...

Headers cannot be set after they have already been sent following the establishment of the content-type

Currently, I'm attempting to retrieve an object from my server's API. This particular API presents the object as a stream. To properly handle the MIME type of the object (which typically ends in .jpg or similar), I want to ensure that the conte ...

Unlock the full potential of knockout.js by mastering how to leverage templates recursively

Given the following model and view model for nested categories: function Category(id, name) { var self = this; self.Id = ko.observable(id || '00000000-0000-0000-0000-000000000000'); self.Name = ko.observable(name); self.children ...

What is the best way to combine elements from different arrays to create a comprehensive listing?

My current function successfully pulls data from another source to create a listing. However, the data I require is spread across multiple arrays, causing some items to be returned as "undefined." At the moment, I am only fetching data from the products a ...

My pathways are clearly mapped out, yet express is returning a frustrating 404 error

After exhausting all the similar posts on StackOverflow without finding a solution... Let's take a look at my app.js, which is the first file that the express library seeks when launching the app right after my server.js file responsible for setting ...

Discovering the current time and start time of today in EST can be achieved by utilizing Moment.js

Need help with creating Start and End Time stamps using Moment.js in EST: Start Time should reflect the beginning of today End Time should show the current time. This is how I have implemented it using moment.js: var time = new Date(); var startTime=D ...

I am facing a recurring issue where I am unable to add new libraries to my node_modules directory due to encountering the same error every time I attempt to

An error occurred after running npm audit --force, causing a dependency issue in my Node_modules 0 verbose cli C:\Program Files\nodejs\node.exe C:\Users\Jenis\AppData\Roaming\npm\node_modules\npm\bin& ...

A guide on invoking a then function following a successful method in Angular JS

When I have two functions and after one completes, I want to use the then method to call the next function. However, I am struggling with getting the correct structure in place. The success method: self.Read_Data = function () { return Ajax.Get({ ...

Oops! Issue: The mat-form-field is missing a MatFormFieldControl when referencing the API guide

I included the MatFormFieldModule in my code like so: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; ...

Troubleshooting the error message: "Unable to add or update a child row due to a foreign key constraint failure"

Currently, I am facing a challenge while trying to perform simultaneous inserts into two tables (parent and child) using PHP. Here's my approach: I first insert a unique number along with the original data into the parent table. Subsequently, I retrie ...

Having trouble displaying results in Vue.js after making an API request?

I am facing challenges in displaying the results using vue.js. The data from my API (ASP.NET CORE) is being retrieved successfully, as shown in my vue dev tools on Google Chrome. However, I am encountering difficulties in rendering the results on the brows ...

Playback on iPhone devices and Safari experiences a 50% reduction with AudioWorklet

I recently developed a basic audio recorder that utilizes the AudioWorkletAPI. While the playback functions smoothly on Chrome, it seems to have issues on Safari and iPhone devices (including Chrome on iPhone) where half of the audio is missing. Specifical ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

Converting input dates in nest.js using TypeScript formatting

Is it possible to set a custom date format for input in nest.js API request body? For example, like this: 12.12.2022 @ApiProperty({ example: 'ADMIN', description: 'Role name', }) readonly value: string; @ApiProperty({ ...