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, ...
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With