Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear all contents of form with JQuery

Is there a method to clear all form elements of a form using JQuery?

Say I have a form like below:

<form id="myForm">
    Name: <input type="text" name="name"/> <br/>
    Message: <input type="text" name="message"/>
    <input type="submit" value="Submit Form"/>
</form>

I could do something like below:

$(document).ready(function() {
    $('#myForm').submit(function(event) {
        event.preventDefault();
        //ajax call here
    }).done(function() {
        $('input[name="name"]').val("");
        $('input[name="message"]').val("");
    });
});

This method clears each form element, but is there a broader method that just clears content of an entire form? Some pseudo like $('#myForm').clearInputs();? If just so it's easier/shorter to clear all elements at once than clear element 1, clear element 2, ...

like image 250
gator Avatar asked Oct 21 '25 00:10

gator


1 Answers

Here is another way that catches radios and checkboxes as well.

$('#myForm').find(':input').each(function() {
    switch (this.type) {
        case 'password':
        case 'select-multiple':
        case 'select-one':
        case 'text':
        case 'textarea':
            $(this).val('');
            break;
        case 'checkbox':
        case 'radio':
            this.checked = false;
    }
});
like image 61
Yes Barry Avatar answered Oct 23 '25 13:10

Yes Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!