Hi I have a form which does update on button click.
$scope.action = "Update";
var id = $routeParams.editId;
scope.item = updateRecord.get({ id: id });
Once the item is updated it doesn't remove the entered information in the form fields. I was wondering what is available in angularjs to add in the above code after udpating so that it also clears to form.
Thanks
You can reset a form by, $scope.formName.$setPristine(); but if you're binding a model object to your inputs, you need to take care of clearing those too, ie:
$scope.currentRecord={};
EDIT
As ToodoN-Mike pointed out, don't forget to set
$scope.formName.$setUntouched()
The $touched flag was introduced in angular 1.3.
At the bottom of your submit function's body run this code below.
// Reset the form model.
vm.project = {};
// Set back to pristine.
vm.form.$setPristine();
// Since Angular 1.3, set back to untouched state.
vm.form.$setUntouched();
"vm.form" is my form name.
For more info have a look at this docs page:
https://docs.angularjs.org/api/ng/type/form.FormController
This worked for me.
viewModel.data = {};
$scope.formName.$setUntouched();
$scope.formName.$setPristine();
1) To Remove the values in Form Fields and to reset you can use $setPristine();
$scope.formName.$setPristine();
2) Next, to set the form to Untouched State too use $setUntouched();
(If you have required fields in your form Fields and also if you are using ng-messages then if you don't use the below function those fields will show error.)
$scope.formName.$setUntouched();
I dont get the question, but maybe, you can clean the form in the Html component:
function: ngSubmit(), send the data.
taskName is the name of the field, also taskBody.
<form (ngSubmit)="onSubmit(taskName.value, taskBody.value); taskName.value=''; taskBody.value=''" #taskForm="ngForm">
Related
I am struggling to figure out a way to trigger these AngularJS classes on a form I am trying to automatically fill with a chrome extension I am making. The form (specifically a textbox) has to be validated/modified before it will be validated and therefore submitted.
I originally tried using javascript to set the value of the textbox using the value property. This did not validate the form. I then tried using a dispatch event to send a key to the textbox, which resulted in nothing being input into the text box. How can I validate the form without requiring human input, or is this not possible?
Clarification, I am trying to replicate this action without user input by using a chrome extension.
Reference https://www.w3schools.com/angular/angular_validation.asp
Sounds like you need to create some events to simulate whatever angular is listening for, probably change or blur. Here's an example using click from mozilla:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#Triggering_built-in_events
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox');
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
How can I validate the form without requiring human input
Get the forms controls:
var controls = $scope.tdForm.$getControls();
Trigger their validators:
controls.forEach( _ => _.$validate() );
From the Docs:
$validate();
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
For more information, see
AngularJS Form Controller API Reference
AngularJS ngModelController API Reference
When you type into the form, it updates the state of its controls (touched, dirty, etc.). According to how you define your fields validators (required, minLength...) the form will be valid or not after the user input.
In your submit method you should not proceed if any form fields are not valid. See AngularJS Developer Guide — Forms or Scotch Tutorials — AngularJS Form Validation you can have more details about AngularJS validation.
As Mike mentioned, you can use ngClass conditionally (see below) to apply some style classes only if a boolean condition occurr, for example the form is not valid.
<div ng-controller="ExampleController">
<form name="form" novalidate class="css-form">
<input type="text" ng-model="user.name" name="username" ng-class="{ 'error': !isValid }"/>
<div ng-show="form.$submitted>
<span ng-show="form.username.$error">Wrong Name</span></span>
</div>
<button ng-click="submit(user)"> Submit </button>
</form>
</div>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.isValid = true;
$scope.submit= function(user) {
if (user.name != 'Carl') {
$scope.isValid = false;
}
};
}]);
You can always programmatically change the form states if needed. For example to set the field to pristine:
$scope.form.$setPristine();
$scope.form.$setUntouched();
$setPristine sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class.
Additionally, it sets the $submitted state to false. This method will also propagate to all the controls contained in this form.
$setUntouched sets the form to its untouched state. This method can be called to remove the 'ng-touched' class and set the form controls to their untouched state (ng-untouched class).
Setting a form controls back to their untouched state is often useful when setting the form back to its pristine state.
UPDATE
Now it is clear what you are attempting to achieve. The two methods above can be used to set the form state, but if you want to validate it from code (this can be done passing the form to a service or directly in the controller for instance) then $validate() method will allow you to achieve that as mentioned by George.
i have created one submission form by using java script i need to reset the input data by using on reset button.
Help me out of this.
reset: function() {
var oInput1 = sap.ui.getCore().byId("firstname");
oInput1.setValue("");*/
this.getViewById("firstname").setValue("");*/
}
input1.getId("firstname").setValue("");
onExit: function() {
input1.setValue("");
}
the code is not resetting the form data
First of all your provided code-sample is incorrect, please correct it.
Second, onExit is executed when your view is destroyed, setting the input value to empty is rather useless there.
If you want to reset data of your input-field when clicking a button you'll need to have the following elements:
1) an Input- & Button-control (with press-event) in your XML-view.
2) an id assigned to your Input-control to be able to refer to the control when pressing the reset-button.
3) The press-event from the button worked out in your controller.
XML
<Input id="firstname" value=""/>
<Button text="Reset" press="reset"/>
Controller
reset: function() {
var oInput1 = this.getView().byId("firstname");
oInput1.setValue("");
}
The issue is when I attempt to resubmit a form without refreshing the page the event handler for the form submission retains the value for the previous submission.
The form contains a select element that is populated with options from an API. The selected option is used to make a request URL and get data from the API. When the form is submitted a second time without refreshing the form. Submit event handler constructs a URL with the previous value and then it constructs a URL with the newly selected value. I have tried to a reset on the form which does reset the select element to its initial state but it does not clear the previously selected value from the submit event handler.
<form id="myform">
<label for="input">Select dog breed!<label>
<select class="breeds"></select>
<input type="submit" value="Enter">
</form>
let $select = $(".breeds");
$select.append($(`<option>select breed</option>`))
for (var i=0; i<=breeds.length; i++){
$select.append($(`<option></option>`).text(breeds[i]).html(breeds[i]))
}
$('.breeds').on('change', function(){
console.log('on change running')
let breed = $(".breeds :selected").text()
console.log(`breed in on change: ${breed}`)
watchForm(breed)
})
function watchForm(breed) {
console.log(`watchForm running`)
console.log(`breed in watchform is: ${breed}`) //here breed logs as the value for first submission and then the second submission
$('form').submit(event => {
console.log(`breed in form submit is ${breed}`)
event.preventDefault();
//console.log(`num is ${num}`)
getDogImage(breed);
$('#myform').get(0).reset()
});
}
Best and simple solution ever
Use trigger()
$('#myform').trigger("reset");
You're good to go!!
You can use something like that. $('myform').val('');
Jquery selector can return one or more element, so it returns an array.
Since reset() is a Javascript function and we are forcefully using it in jquery, it requires a specific element to perform reset action.
$('#myform')[0].reset()
Using vanilla Javascript is the easiest and simplest one because id is unique in a HTML document.
document.getElementById("myForm").reset();
So let us say i have a form with id #form which has two input fields, namely title & price.
I click on the Edit button somewhere in the application which has data attributes (e.g data-title="Apple" data-price="10")that are to be assigned to the #form upon clicking the button.
the obvious solution that works is
$("#name").val($(this).data('name'));
$("#price").val($(this).data('price'));
This obviously looks bad when you have too many fields. So I am trying to get something like this to work $('#form').data($(this).data());, more or less in a single like
Have tried this many ways with no success
Any help is appreciated
You could create a jquery plugin that you can call from the element that contains the data points and have it apply the data based on the key to elements within the form of that same name. Example below
$.fn.applyData = function(form) {
$form = $(form);
$.each($(this).data(), function(i, key) {
$form.find('#' + i).val(key);
});
};
JSFiddle: http://jsfiddle.net/LCM8S/43/
I have a bunch of inputs, i'd like to call reset but there are all outside of a form. I tried calling reset on input and textarea with no luck.
Is there a similar function i can use?
Keep in mind that the form RESET actually doesn't clear all fields, it will reset a form's default values back to default as well, so a better approach might be the following:
$('#the_form').trigger('reset');
Perhaps another approach:
// capture all existing values
var arr = [];
$(':input').each(function(i, e)
{
arr.push($(e).val());
});
// custom function to reset all values to initially captured values
function my_reset()
{
$(':input').each(function(i, e)
{
$(e).val(arr[i]);
});
}
The above approach blindly targets all fields, if you have a way to better target them, you should definitely use what you can.
Additionally, this approach stores all the fields in order, so if you have dynamically generated fields, then this solution would have to be revised.
My approach (second to putting them in a form...) would be to, onload, map the default values to each input id or name, and then create a reset method that just iterates that collection, get by id and set to default...
Do you want to reset or just to clear the inputs?
Reset would be more complicated, but clearing in your case is easy:
HTML:
<input type="text"/>
<textarea></textarea>
<button id="resetBtn">Reset</button>
JS:
$("#resetBtn").click(function(){
$("input, textarea").val("");
});