I am trying to use jQuery to do a simple thing: clear the input fields of a group of input field within a div whenever the form loads, or if the user changes a picklist; but
Couple issues that I see. fetch_results
is a class, not an Id and the each function doesn't look right.
$('.fetch_results:input').each(function() {
$(this).val('');
});
Just be sure to remember that if you end up with radios or check buttons, you will have to clear the checked attribute, not the value.
If you wanted to stay with a class level selector then you could do something like this (using the same jfiddle from Mahn)
$("div.fetch_results input:text").each(function() {
this.value = "testing";
})
This will select only the text input boxes within the div with a fetch_results class.
As with any jQuery this is just one way to do it. Ask 10 jQuery people this question and you will get 12 answers.
For some who wants to reset the form can also use type="reset"
inside any form.
<form action="/action_page.php">
Email: <input type="text" name="email"><br>
Pin: <input type="text" name="pin" maxlength="4"><br>
<input type="reset" value="Reset">
<input type="submit" value="Submit">
</form>
$.each($('.fetch_results input'), function(idx, input){
$(input).val('');
});
inspired from https://stackoverflow.com/a/10892768/2087666 but I use the selector instead of a class and prefer if over switch:
function clearAllInputs(selector) {
$(selector).find(':input').each(function() {
if(this.type == 'submit'){
//do nothing
}
else if(this.type == 'checkbox' || this.type == 'radio') {
this.checked = false;
}
else if(this.type == 'file'){
var control = $(this);
control.replaceWith( control = control.clone( true ) );
}else{
$(this).val('');
}
});
}
this should take care of almost all input inside any selector.
Fiddle: http://jsfiddle.net/simple/BdQvp/
You can do it like so:
I have added two buttons in the Fiddle to illustrate how you can insert or clear values in those input fields through buttons. You just capture the onClick event and call the function.
//Fires when the Document Loads, clears all input fields
$(document).ready(function() {
$('.fetch_results').find('input:text').val('');
});
//Custom Functions that you can call
function resetAllValues() {
$('.fetch_results').find('input:text').val('');
}
function addSomeValues() {
$('.fetch_results').find('input:text').val('Lala.');
}
Update:
Check out this great answer below by Beena as well for a more universal approach.