Clear form fields with jQuery

616    Asked by DeirdreCameron in Python , Asked on Jul 5, 2021

I want to clear form fields with jQuery, 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?


Answered by Carolyn Buckland

For jQuery 1.6+ version, you can try using the code given below :

$(':input','#myform')
  .not(':button, ubmit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);
For more jQuery related information, refer to this document: https://api.jquery.com/attr/
For jQuery < 1>

$('#myform')[0].reset();According to jQuery:

To retrieve and change the DOM properties such as the checked, selected, or disabled state of form elements, you can use the .prop() method.

Additional: How do you reset form fields?

Form reset() Method: The reset() method resets the values of all elements in a form (same as clicking the Reset button). Tip: Use the submit() method to submit the form.



Your Answer