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("");
});
Related
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();
I am not sure whether its logical to get.
Here is the html code for my input box.
<input type="text" id="name" #name="ngForm" [ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event,'name')"
/>
and here is my firechange function
firechange($event, field){
if(this.userProfileForm.controls[field].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
I want to pass only the event in the firechange function and inside the fire change function I want to get the input field name from the event so that I can understand that which input field in my form triggered the event. Expected code will be something like that
[ngFormControl]="userProfileForm.controls['name']"
[(ngModel)]="loggedUserInfo.name" (change)="firechange($event)"
/>
firechange($event){
if(this.userProfileForm.controls[$event.fieldname].valid){
this._userService.updateUserProfile(this.loggedUserInfo);
this._userService.loadUserData();
}
}
My ideal requirement is, in a form there are number of form fields, I don't even want to write firechange function in each individual form field. Is there any generic way to call the event on each input field value change for a particular form without writing it on each input field?
To get the actual name of the element you can do the following:
firechange(event){
var name = event.target.attributes.getNamedItem('ng-reflect-name').value;
console.log('name')
}
If the id is the same as the name you are passing you can get the name like
firechange(event){
if(this.userProfileForm.controls[$event.target.id].valid){
}
If you want to get hold of the element from within your fire change function you may want to try something like:
firechange(event){
let theElement = event.target;
// now theElement holds the html element which you can query for name, value and so on
}
If you in addition you want to instruct your component to apply the firechange() logic on all of your input fields with one single instruction in your component (and not having to specify this on every single input field) than I suggest you to look at in Angular2 how to know when ANY form input field lost focus.
I hope this helps
If id is not the same or it can change, here's more leverage...
You may want to reflect the [name] property the the element's attribute:
... #input [name]="item.name" [attr.name]="item.name" (change)="fn(input)" ...
Then,
...
fn(input) {
log(input.name); // now it returns the name
}
...
See more here
Try this:
<input type="text" (change)="firechange($event.target.value)">
This worked for me in Angular 10
$event.source.name
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">
I am not sure how to phrase what I'm asking (or I would probably be able to find it). What is it called when you have an indefinite number of items to add to a webpage form for submission to a db? For example, if you have a resume web site, and you want to add experience. You may have a slot for one job, and an "Add more experience" to that. What is that called? How do you implement that (js, html, css)?
EDIT:
Thanks for the comments. This is called: dynamically add form elements.
this is a basic idea ,,
http://jsfiddle.net/3mebW/
var noOfFields = 2;
$('#addNew').on('click', function(e) {
e.preventDefault();
var newField = '<br><label for="experience'+noOfFields+'">experience'+noOfFields+'</label>';
newField += '<input type="text" name="experience'+noOfFields+'"class="field"/>';
$('.field:last').after(newField);
//adding a hidden input inside the form to know the number of inserted fields
//make sure that the input is not already here
//then adding it to handle the number of inputs later
if($('#noOfFields').length === 0){
$('#Frm').append('<input type="hidden" value="2" id="noOfFields"/>');
}else{
$('#noOfFields').attr('value',noOfFields);
}
noOfFields++;
});
you can also detect the number of fields using a class or any other method
You can do this using the jQuery function .clone().
Here's the jQuery doc about it : http://api.jquery.com/clone/
You can copy your Experience input field, and set its properties (ID, name, etc) before appending it where you want.
lots of ways to do this, here is is one
http://jsfiddle.net/uuKM8/
$('#myBtn').click(function(){
$( "#myInput" ).clone().appendTo('body');
});
All,
I can reset all my form elements using the following JQuery Syntax:
('#myform')[0].reset();
How can I modify this to exclude the reset of "select box" values?
Thanks
To everyone..
the reset function does not set everything to '' (empty string)
it reset to their initial values .. (stored in the value attribute, or selected option etc..)
If you want to maintain the default reset features then you should
get all the <select> elements
get their currently selected values
reset the form as you currently do
re-set the selected
example:
<script type="text/javascript">
$(document).ready(
function(){
$("#resetbutton").click(
function(){
var values = [];
var selected = $("select").each(
function(){
values.push( $(this).val());
});
this.form.reset();
for (i=0;i<selected.length;i++)
$(selected[i]).val(values[i]);
});
}
);
</script>
That's not jQuery, it's native javascript. [0] brings out the actual DOM element, so it's the same as:
document.getElementById('myform').reset();
reset() is a built-in browser implementation that resets the entire form. If you need to reset individual form types, try something like:
$('#myform :text').val('');
You can see all form selectors here: http://docs.jquery.com/Selectors
You can do a fake reset by setting the values to an empty string and resetting the checkboxes using David's answer (or this more complete one). You could also try storing each select element's value before resetting the form and then restore the values after:
var myform = $('#myform');
var selects = $('select', myform);
// Store each current value
selects.each(function() {
$(this).data('previous', $(this).val());
});
myform[0].reset();
// Restore the values
selects.each(function() {
$(this).val($(this).data('previous'));
});
For whatever reason, David's right-on answer error'd my Google Chrome js. It's saying:
Uncaught TypeError: Property 'reset' of object # is not a function
...so I decided to try a slightly different solution:
Give native browser reset buttons attributes "hidden" and set "id":
<input id="resetbutton" type="reset" style="visibility:hidden;" name="reset" value="reset" />
Initiate JQuery "click" event on reset button from clicking link:
Reset