Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

I want to clear 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?

2 Answers

0 votes
by (40.7k points)

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

$(':input','#myform')

  .not(':button, :submit, :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.6 version, use this code:

$(':input','#myform')

  .not(':button, :submit, :reset, :hidden')

  .val('')

  .removeAttr('checked')

  .removeAttr('selected');

Refer to this document: Resetting a multi-stage form with jQuery

Or, use this code:

$('#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.

0 votes
by (1.9k points)

If we want to clear the input form fields, jQuery provides a method named ".val()"

This method can used to set the input fields to an empty string.

$('#userForm').find('input[type="text"], input[type="text"], textarea').val(' '); 

Using the .val() method we have set the fields to an empty string. 

This way the form fields are cleared.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 28, 2019 in Web Technology by Tech4ever (20.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...