How to reset a form using jQuery with .reset() method
I've finally solve the problem!!
@RobG was right about the form
tag and table
tag. the form
tag should be placed outside the table. with that,
<td><input type="reset" id="configreset" value="Reset"></td>
works without the need of jquery or anything else. simple click on the button and tadaa~ the whole form is reset ;) brilliant!
Reset a form with Jquery
The .reset()
method is not a jQuery method, and that's why it wouldn't work with a jQuery object. You can, however, refer to the DOM node in the jQuery object and then use the native JS method on it, i.e.: $("form")[0].reset();
.
define(["jquery"], function($) {
return function() {
$("form").on("submit", function() {
if (!$("form-group").hasClass("has-errors") && !$("div").hasClass("alert")){
$("form")[0].reset();
}
});
}
})
However, I generally consider a form reset button unnecessary and in fact, detrimental to user experience. For majority (I'd say 99.9%) of use cases, when a user starts typing in a form they do not have the intention of completely erasing their data, and so the reset button, when clicked on by mistake (especially if the action is not made clear through UI design), will erase the user's input much to their frustration (and with no "undo" recourse).
Clear form fields with jQuery
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], textarea").val("");
});
How to reset (clear) form through JavaScript?
form.reset()
is a DOM element method (not one on the jQuery object), so you need:
$("#client.frm")[0].reset();
//faster version:
$("#client")[0].reset();
Or without jQuery:
document.getElementById("client").reset();
Note: reset() function does not work if form contains any field with attribute:
name='reset'
Resetting Values using jquery
One option to remove the value of input is to use .val("")
. Basically setting the value to an empty string.
Here is an example:
$(document).ready(function() { $("#reset_btn").click(function() { $("#buy").val(""); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy">
<button type="button" class="btn btn-secondary" id="reset_btn">RESET</button>
How to reset form to last saved(through ajax) stage
Thanks for your responses guys.
I tried to implement a solution based on madalin ivascu's comment. Also found a jsfiddle to do the same. With some modifications/changes I got what I needed.
Step 1: Write a custom plugin:
(function($) {
$.fn.deserialize = function (serializedString) {
var form = jQuery(this);
form[0].reset();
serializedString = serializedString.replace(/\+/g, "%20");
var formFieldArray = serializedString.split("&");
jQuery.each(formFieldArray, function(i, pair) {
var nameValue = pair.split("=");
var name = decodeURIComponent(nameValue[0]);
var value = decodeURIComponent(nameValue[1]);
var field = form.find("[name='" + name + "']");
if (field[0] != undefined) {
if (field[0].type == "radio" || field[0].type == "checkbox") {
var fieldWithValue = field.filter('[value="' + value + '"]');
var isFound = (fieldWithValue.length > 0);
if (!isFound && value == "on") {
field.first().prop("checked", true);
} else {
fieldWithValue.prop("checked", isFound);
}
} else {
field.val(value);
}
}
});
}
}(jQuery));
Step 2: Save serialized form data somewhere.
When you need to reset form to last saved stage, use this:
yourForm.deserialize(serializedFormData);
jQuery / javascript cannot reset a form
Quite likely you have:
<input type="reset" name="reset" id="reset"/>
The problem is with name="reset"
. In JS form.reset
refers to this DOM element and therefore causes a name conflict with the reset()
method.
Therefore form.reset()
----> TypeError: $(...)[0].reset is not a function
means just that.
$('#reset').on('click', function() { $('form')[0].reset();});
input[name=reset] { display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><form> <input type="radio" name="gender" value="A"/> A <input type="radio" name="gender" value="B"/> B <input type="radio" name="gender" value="C"/> C <input type="reset" name="reset"/> <button id="reset">Click To Reset</button></form>
Resetting a multi-stage form with jQuery
updated on March 2012.
So, two years after I originally answered this question I come back to see that it has pretty much turned into a big mess. I feel it's about time I come back to it and make my answer truly correct since it is the most upvoted + accepted.
For the record, Titi's answer is wrong as it is not what the original poster asked for - it is correct that it is possible to reset a form using the native reset() method, but this question is trying to clear a form off of remembered values that would remain in the form if you reset it this way. This is why a "manual" reset is needed. I assume most people ended up in this question from a Google search and are truly looking for the reset() method, but it does not work for the specific case the OP is talking about.
My original answer was this:
// not correct, use answer below
$(':input','#myform')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
Which might work for a lot of cases, including for the OP, but as pointed out in the comments and in other answers, will clear radio/checkbox elements from any value attributes.
A more correct answer (but not perfect) is:
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
// to call, use:
resetForm($('#myform')); // by id, recommended
resetForm($('form[name=myName]')); // by name
Using the :text
, :radio
, etc. selectors by themselves is considered bad practice by jQuery as they end up evaluating to *:text
which makes it take much longer than it should. I do prefer the whitelist approach and wish I had used it in my original answer. Anyhow, by specifying the input
part of the selector, plus the cache of the form element, this should make it the best performing answer here.
This answer might still have some flaws if people's default for select elements is not an option that has a blank value, but it is certainly as generic as it is going to get and this would need to be handled on a case-by-case basis.
Related Topics
Fastest Way to Convert JavaScript Nodelist to Array
What Benefits Does Es2015 (Es6) 'Class' Syntax Provide
How to Get a Word Under Cursor Using JavaScript
Getting a Better Understanding of Callback Functions in JavaScript
Hide Scrollbar While Still Being Able to Scroll with Mouse/Keyboard
How to Format/Tidy/Beautify in JavaScript
Make Anchor Link Go Some Pixels Above Where It's Linked To
Jquery: How to Change Tag Name
How to Use JSON File in HTML Code
How to Check If a JavaScript Object Is a Dom Object
Verify If a Point Is Land or Water in Google Maps
Using Settimeout on Promise Chain
Difference Between HTMLcollection, Nodelists, and Arrays of Objects
Access Iframe Elements in JavaScript
How to Figure Out the Highest Z-Index in Your Document
Jquery $("#Radiobutton").Change(...) Not Firing During De-Selection