Advertisement
Advertisement


Clear form fields with jQuery


Question

I want to clear all input and textarea fields in a form. It works like the following when using an input button with the reset class:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

This will clear all fields on the page, not just the ones from the form. How would my selector look like for just the form the actual reset button lives in?

2013/03/10
1
408
3/10/2013 9:07:19 PM

Accepted Answer

$(".reset").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});
2011/06/15
493
6/15/2011 9:04:06 PM


Any reason this shouldn't be used?

$("#form").trigger('reset');
2013/03/17

This won't handle cases where form input fields have non empty default values.

Something like should work

$('yourdiv').find('form')[0].reset();
2011/06/15

if you use selectors and make values to empty values, it is not resetting the form, it's making all fields empty. Reset is to make form as it was before any edit actions from user after the load of form from server side. If there is an input with name "username" and that username was prefilled from server side, most of solutions on this page will delete that value from input, not reset it to the value how it was before user's changes. If you need to reset the form, use this:

$('#myform')[0].reset();

if you need not to reset the form, but fill all inputs with some value, for example empty value, then you can use most of the solutions from other comments.

2014/10/18

If someone is still reading this thread, here is the simplest solution using not jQuery, but plain JavaScript. If your input fields are inside a form, there is a simple JavaScript reset command:

document.getElementById("myform").reset();

More about it here: http://www.w3schools.com/jsref/met_form_reset.asp

Cheers!

2018/01/03

Simple but works like a charm.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS
2014/06/03

Source: https://stackoverflow.com/questions/6364289
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]