moses toh
moses toh

Reputation: 13172

How can I clear form when button clicked?

My code like this :

$('body').on('click', '#add-image', function(e) {
    $(this).find('#form-add').trigger('reset');
    // $(this).find('#form-add').clearForm();
    // $('#form-add').clearForm();
    // $('#form-add').val("");
    // ...
});

If button clicked, I want the form clear

I try like that, but it does not work

How can I solve this problem?

Upvotes: 0

Views: 86

Answers (5)

Daniel Taub
Daniel Taub

Reputation: 5369

You can clean all the text fides that undet that form like that :

$("#clean").click(function() {
    $(this)
    .closest('form')
    .find("input[type=text],textarea")
    .val('');
});

Upvotes: 0

prasanth
prasanth

Reputation: 22490

Try with empty() function jquery

$('body').on('click', '#add-image', function(e) {
    $(this).find('#form-add').trigger('reset');
     $(this).find('#form-add').find('input,textarea').empty()
});

Upvotes: 0

Bitito
Bitito

Reputation: 201

Yes you can reset a form, is almost the same as clean.

Pure JS:

document.getElementById('THE-FORM-ID').reset();

DEMO: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_form_reset

Upvotes: 0

utkarsh31
utkarsh31

Reputation: 1549

Let us suppose you have a button with class clearAll, call the below jquery function which will clear all the textfields and textarea at once...easier and simple...customize however you want...

$(".clearAll").click(function() {
    $(this).closest('form').find("input[type=text], textarea").val("");
});

Upvotes: 0

Koby Douek
Koby Douek

Reputation: 16675

Clearing an entire form with Javascript or JQuery, it's recommended that you
explicitly clear each of your elements.

For example, clearing all text inputs:

$('#txtbox1').val('');
$('#txtbox2').val('');
etc. etc.

Another less recommended alternative is to use reset():

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

But this does not 100% guarantee clearing all elements within, since some of the elements may not be scoped within your form.

Upvotes: 2

Related Questions