Clear form after submit - javascript

I am submitting a form - and adding the contents to an array, however whenever the item is added to the array, it is still bound to the form.
I would like to add the item, clear the form. Something like jquery's reset();
Here's my template:
<div class="col-xs-12" ng-controller="ResourceController">
<div class="col-md-4">
<h3>Name</h3>
</div>
<div class="col-md-8">
<h3>Description</h3>
</div>
<form class="form-inline" role="form" ng-repeat="item in resources">
<div class="form-group col-md-4">
<input type="text" class="form-control" value="{{ item.name }}"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" value="{{ item.description }}"/>
</div>
</form>
<form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
<div class="form-group col-md-4">
<input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
</div>
<div class="form-group col-md-7">
<input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
</div>
<div class="form-group col-md-1">
<button type="submit" class="btn btn-default">Add</button>
</div>
</form>
</div>
And my controller:
(function(){
var app = angular.module('event-resources', []);
app.controller('ResourceController', function($scope){
$scope.addResource = function(){
$scope.resources.push(this);
}
var defaultForm = {
name : '',
description: ''
};
$scope.resources = [
{
name: 'Beer',
description: 'Kokanee'
},
{
name: 'Pucks',
description: 'Black Round Things'
}
]
});
})();

Use angular.copy() to copy the item data to the resources array, and then you can safely clear the item data. The angular.copy() makes a deep copy of the object, which is what you want.
Alternately, here is a simpler method, which doesn't use any extra method calls:
$scope.addResource = function() {
$scope.resources.push({
name: $scope.name, // recreate object manually (cheap for simple objects)
description: $scope.description
});
$scope.name = ""; // clear the values.
$scope.description = "";
};

$scope.addResource = function(){
$scope.resources.push(angular.copy(this));
$scope.name="";
$scope.description=""
}
Push the copy to the resources array and change name and description back to ""

Related

AngularJS 1.6.8: Form data not submitting and so hence unable to save it to localStorage

I have a contact form. On submission, it displays a success message and it should store that data to $localStorage.
But, Form data not is not submitting as I do not see submitted form data in response under network in dev tools and hence I am unable to save it to $localStorage.
below is the code for respective files.
link to plunker
contact.html
<div ngController="contactController as vm">
<div class="heading text-center">
<h1>Contact Us</h1>
</div>
<div>
<form class="needs-validation" id="contactForm" novalidate method="post" name="vm.contactForm" ng-submit="saveform()">
<div class="form-group row">
<label for="validationTooltip01" class="col-sm-2 col-form-label">Name</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipName" placeholder="Name" ng-model="vm.name" required>
<div class="invalid-tooltip">
Please enter your full name.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltipEmail" class="col-sm-2 col-form-label">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="validationTooltipUsernamePrepend">#</span>
</div>
<input type="email" class="form-control" id="validationTooltipEmail" placeholder="Email"
aria-describedby="validationTooltipUsernamePrepend" ng-model="vm.email" required>
<div class="invalid-tooltip">
Please choose a valid email.
</div>
</div>
</div>
<div class="form-group row">
<label for="validationTooltip03" class="col-sm-2 col-form-label">Query</label>
<div class="input-group">
<input type="text" class="form-control" id="validationTooltipQuery" ng-model="vm.query" placeholder="Query" required>
<div class="invalid-tooltip">
Please write your Query.
</div>
</div>
</div>
<div class="btn-group offset-md-5">
<button class="btn btn-primary" type="submit">Submit</button>
<button class="btn btn-default" type="button" id="homebtn" ng-click="navigate ('home')">Home</button>
</div>
</form>
<span data-ng-bind="Message" ng-hide="hideMessage" class="sucessMsg"></span>
</div>
</div
contact.component.js
angular.module('myApp')
.component('contactComponent', {
restrict: 'E',
$scope:{},
templateUrl:'contact/contact.html',
controller: contactController,
controllerAs: 'vm',
factory:'userService',
$rootscope:{}
});
function contactController($scope, $state,userService) {
var vm = this;
vm.saveform = function(){
var name= vm.name;
var email= vm.email;
var query= vm.query;
console.log(name);
console.log(email);
console.log(query);
$scope.hideMessage = false;
$scope.Message = "Your query has been successfully submitted.";
$scope.user = userService;
};
$scope.navigate = function(home){
$state.go(home)
};
};
//localStorage code
function userService(saveform) {
var service = {
model: {
name: '',
email: '',
query:''
},
SaveState: function () {
sessionStorage.userService = angular.toJson(service.model);
},
RestoreState: function () {
service.model = angular.fromJson(sessionStorage.userService);
}
}
$rootScope.$on("savestate", service.SaveState);
$rootScope.$on("restorestate", service.RestoreState);
return service;
$rootScope.$on("$routeChangeStart", function (event, next, current) {
if (sessionStorage.restorestate == "true") {
$rootScope.$broadcast('restorestate'); //let everything know we need to restore state
sessionStorage.restorestate = false;
}
});
//let everthing know that we need to save state now.
window.onbeforeunload = function (event) {
$rootScope.$broadcast('savestate');
};
};
There are no errors in console.

Dynamically display form data using AngularJS

I would like to dynamically display Person and Address data using label and input value in Summary Section. As the user edits the form fields, a list items with label + value should display in the summary tables. If value has been removed in the form, that associated label and value should be removed from the Summary Section.
I have added client side validation for each input element. I tried to solve this and couldn't figure out what is best way to do it. Any help would be appreciated.
Example:
// the main (app) module
var myApp = angular.module("myApp", []);
// add a controller
myApp.controller("myCtrl", function($scope) {
$scope.vm = {
caller: {
person: {
firstName: '',
lastName: '',
phoneOne: '',
email: ''
},
address: {
lineOne: '',
lineTwo: ''
}
}
};
$scope.save = function() {
console.log($scope.vm);
}
});
// add a directive
myApp.directive('showErrors', function($timeout, $compile) {
return {
restrict: 'A',
require: '^form',
link: function(scope, el, attrs, formCtrl) {
// find the text box element, which has the 'name' attribute
var inputEl = el[0].querySelector("[name]");
// convert the native text box element to an angular element
var inputNgEl = angular.element(inputEl);
// get the name on the text box
var inputName = inputNgEl.attr('name');
// only apply the has-error class after the user leaves the text box
var blurred = false;
inputNgEl.bind('blur', function() {
blurred = true;
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
scope.$watch(function(scope) {
return formCtrl[inputName].$invalid;
}, function(invalid, scope) {
// we only want to toggle the has-error class after the blur
// event or if the control becomes valid
if (!blurred && invalid) {
return
}
el.toggleClass('has-error', invalid);
});
scope.$on('show-errors-check-validity', function() {
el.toggleClass('has-error', formCtrl[inputName].$invalid);
});
scope.$on('show-errors-reset', function() {
$timeout(function() {
el.removeClass('has-error');
}, 0, false);
});
}
}
});
.form-group .help-block {
display: none;
}
.form-group.has-error .help-block {
display: inline;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<form name="claimForm" ng-submit="save()">
<h3>PERSON</h3>
<div class="col-md-6">
<div class="form-group form-caller" show-errors>
<label class="control-label">First Name<span class="help-block" ng-if="claimForm.callerFirstName.$error.required"><i>[required]</i></span>
</label>
<input type="text" name="callerFirstName" ng-model="vm.caller.person.firstName" class="form-control" required="" />
</div>
</div>
<div class="col-md-6">
<div class="form-group form-caller" show-errors>
<label class="control-label">Last Name<span class="help-block" ng-if="claimForm.callerLastName.$error.required"><i>[required]</i></span>
</label>
<input type="text" name="callerLastName" ng-model="vm.caller.person.lastName" class="form-control" required="" />
</div>
</div>
<hr />
<h3>ADDRESS</h3>
<div class="col-md-6">
<div class="form-group" show-errors>
<label class="control-label">Address Line 1<span class="help-block" ng-if="claimForm.addressOne.$error.required"><i>[required]</i></span>
</label>
<input type="text" name="addressOne" ng-model="vm.caller.address.lineOne" class="form-control" required="" />
</div>
</div>
<div class="col-md-6">
<div class="form-group" show-errors>
<label class="control-label">Address Line 2<span class="help-block" ng-if="claimForm.addressTwo.$error.required"><i>[required]</i></span>
</label>
<input type="text" name="addressTwo" ng-model="vm.caller.address.lineTwo" class="form-control" required="" />
</div>
</div>
<hr />
<input type="submit" id="submit" value="SUBMIT" class="btn btn-primary btn-lg" />
{{vm | json }}
</form>
<h2>Summary</h2>
<div id="person">
<h3>PERSON </h3>
</div>
<hr />
<div id="address">
<h3>ADDRESS</h3>
</div>
</body>
Thanks in Advance

How to clear angularJS form after submit?

I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.

Part's of form not being rendered - AngularJS

I can't seem to find why the "start" and "finish" part of my form isn't being rendered. This is the first time I've ever worked with AngularJS, and after following quite a few tuts online, I used to yo meanjs generator with the articles example. I then took the articles example and tried to port it over to this scheduling thing. It really doesn't matter though, I just want to know why the last two inputs in the form aren't being rendered in my view.
Any help is much appreciated
Here's the code for my view:
<section data-ng-controller="SchedulesController">
<div class="page-header">
<h1>New Schedule</h1>
</div>
<div class="col-md-12">
<form name="scheduleForm" class="form-horizontal" data-ng-submit="create()" novalidate>
<fieldset>
<div class="form-group" ng-class="{ "has-error": scheduleForm.title.$dirty && scheduleForm.title.$invalid }">
<label class="control-label" for="title">Title</label>
<div class="controls">
<input name="title" type="text" data-ng-model="title" id="title" class="form-control" placeholder="Title" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="content">Content</label>
<div class="controls">
<textarea name="content" data-ng-model="content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label" for="start">Start</label>
<div class="controls">
<input name="finish" value="" type="date" data-ng-model="start" class="form-control" required>
</div>
</div>
<div class="form-group">
<label class="control-label" for="finish">Finish</label>
<div class="controls">
<input name="finish" value ="" type="date" data-ng-model="finish", class="form-control" required>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-default">
</div>
<div data-ng-show="error" class="text-danger">
<strong data-ng-bind="error"></strong>
</div>
</fieldset>
</form>
</div>
</section>
Here's the code for my controller:
'use strict';
angular.module('schedules').controller('SchedulesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Schedules',
function($scope, $stateParams, $location, Authentication, Schedules) {
$scope.authentication = Authentication;
$scope.create = function() {
var schedule = new Schedules({
title: this.title,
content: this.content,
start: this.start,
finish: this.finish
});
schedule.$save(function(response) {
$location.path('schedules/' + response._id);
console.log('hola!');
$scope.title = '';
$scope.content = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.remove = function(schedule) {
if (schedule) {
schedule.$remove();
for (var i in $scope.schedules) {
if ($scope.schedules[i] === schedule) {
$scope.schedules.splice(i, 1);
}
}
} else {
$scope.schedule.$remove(function() {
$location.path('schedules');
});
}
};
$scope.update = function() {
var schedule = $scope.schedule;
schedule.$update(function() {
$location.path('schedules/' + schedule._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.schedules = Schedules.query();
};
$scope.findOne = function() {
$scope.schedule = Schedules.get({
scheduleId: $stateParams.scheduleId
});
};
}
]);
Um... Well guys.... I don't know WHY this worked, and everything in me tells me this wasn't the problem, BUT:
Notice line
<input name="finish" value ="" type="date" data-ng-model="finish", class="form-control" required>
The "," was a mistake (I wrote a script that ported everything from articles into schedule, maintining code structure and just changing all mentions of [Aa]rticle{s} -> [Ss]chedule{s}, and this was left over in that (for some reason, don't know where it came in). Anyway, I deleted the comment and ran grunt build && grunt test && grunt and it worked. I'm now getting the correct render.

Angular js not retrieving value by id's for dropdowns

I have an angular app with the following function:
$scope.search= function(){
var lname = document.getElementById("lastname").value;
var campus2 = document.getElementById("campusid").value;
StudentSearchService.getStudents(lname, campus2, function(data){
if(data!=null){
$scope.students = data;
}
});
}
and in the html page, I have the following 2 fields:
<div class="form-group col-lg-4 col-md-4">
<label for="lastname"> Last Name: </label>
<input type="text" id="lastname" placeholder="Last Name" class="form-control" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus"> Campus:</label>
<select class="form-control" id="campusid" ng-model="newcampus" ng-options="camp.name for camp in campus" >
<option value="">ALL - District</option>
</select>
</div>
When i click to Search, the value for the lname is being retrieved just fine but the value from the dropdown campus2 is not being being initialized. Thus the call to the service is not being made properly.
Where am I going wrong?
First, it is not necessary to pick values from DOM elements if you are using Angular. It is way more easier to bind variables and use the variables themselves. I have created your example in JSFiddle: http://jsfiddle.net/rmadhuram/1n14eqfw/2/
HTML:
<div ng-app="app" ng-controller="FormController">
<div class="form-group col-lg-4 col-md-4">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" ng-model="lastName" placeholder="Last Name" class="form-control" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus">Campus:</label>
<select class="form-control" id="campusid" ng-model="newcampus" ng-options="camp.name for camp in campus">
</select>
</div>
<button ng-click='search()'>Search</button>
</div>
JavaScript:
angular.module('app', [])
.controller('FormController', ['$scope', function ($scope) {
$scope.campus = [
{ name: 'campus 1' },
{ name: 'campus 2' }
];
$scope.newcampus = $scope.campus[0];
$scope.lastName = '';
$scope.search = function() {
alert('Name: ' + $scope.lastName + ' Campus: ' + $scope.newcampus.name);
};
}]);
Hope this helps!
The biggest place you are going wrong is by trying to access values directly from the DOM inside your Angular controller, rather than relying on Angular to bind properties on the scope to your inputs and handle all of that for you.
I have made a version in Plunkr that demonstrates the "Angular way" of approaching this.
The guts of the controller is:
app.controller('MainCtrl', function($scope, StudentSearchService) {
$scope.campus = [
{name: "Campus 1"},
{name: "Campus 2"}
];
$scope.searchParams = {
lastName: "",
campus: null
};
$scope.search = function() {
StudentSearchService.getStudents($scope.searchParams.lastName,
$scope.searchParams.campus.name,
function(data) {
if (data !== null) {
$scope.students = data;
}
});
}
});
And then your markup becomes:
<div class="form-group col-lg-4 col-md-4">
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" placeholder="Last Name" class="form-control" ng-model="searchParams.lastName" />
</div>
<div class="form-group col-lg-4 col-md-4">
<label for="campus">Campus:</label>
<select class="form-control" id="campusid" ng-model="searchParams.campus" ng-options="camp.name for camp in campus">
<option value="">ALL - District</option>
</select>
</div>
Note the use of ng-model to bind the inputs to scope properties. Also note there is no DOM access code in the controller. This makes it easier to test, and allows you to test your controller without any DOM at all. That is the core philosophy Angular is based around.

Categories

Resources