How do I clear form fields using jQuery?

There is a page in which there are a number of different elements. It is necessary to return them to their original state (as when loading the page). It's not nice to do that:

$('#name').val('');

For each form? Do you have any options on how to make it more beautiful?

Author: Nicolas Chabanovsky, 2011-04-26

8 answers

Listen, well, make your own modifier, add some class to all the necessary elements and clear them with one line, as in the previous tip. What is this quest for the unknown-the magnificent?

 5
Author: Tim Rudnevsky, 2011-07-15 17:42:27

If there is a form:

<form id="myform">
...
</form>

Then you can clear it using javascript:

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

Or jQuery:

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

Updated from the comment.

Then as an option

$(function () {
    $(набор_элементов).each(function () {
        $(this).data('defvalue', this.value);
    });
});

And then call

$(набор_элементов).each(function () {
    $(this).val($(this).data('defvalue'));
});
 9
Author: ling, 2011-07-15 17:46:34
$("form#id_form").trigger('reset');
 4
Author: Galina Bublik, 2017-08-03 13:39:40

Alternatively, create a list of fields (and possibly default values, if not empty), then, if necessary, set all the items in the list to the appropriate values... For example, as suggested by ling...

 2
Author: gote, 2011-07-15 17:43:19

Try this option:

<script>
    jQuery(document).ready(function() {
      $('input').val('');
    });
</script>
 2
Author: AHXAOC, 2011-07-15 17:47:02
$(".reset-form-button").click(function() {

    $("form")[0].reset();

});
 2
Author: Human, 2016-07-03 11:50:01

$('input[name*= "field_name"]'). val(");

 1
Author: Павел Антонов, 2017-06-21 06:20:31

Try this way: $("*[tag='tag']").val("").attr("checked", false);

 1
Author: Domer, 2017-08-03 13:48:40