Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear form fields with jQuery

Tags:

html

jquery

forms

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?

like image 762
tbuehlmann Avatar asked Jun 15 '11 20:06

tbuehlmann


People also ask

How can we make all fields empty in jQuery?

bind("click", function() { $("input[type=text], textarea"). val(""); }); This will clear all fields on the page, not just the ones from the form.

How do I remove all fields in form?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.

How do you reset form fields?

You can easily reset all form values using the HTML button using <input type=”reset”> attribute. Clicking the reset button restores the form to its original state (the default value) before the user started entering values into the fields, selecting radio buttons, checkboxes, etc. There could be many scenarios.


1 Answers

For jQuery 1.6+:

$(':input','#myform')   .not(':button, :submit, :reset, :hidden')   .val('')   .prop('checked', false)   .prop('selected', false); 

For jQuery < 1.6:

$(':input','#myform')   .not(':button, :submit, :reset, :hidden')   .val('')   .removeAttr('checked')   .removeAttr('selected'); 

Please see this post: Resetting a multi-stage form with jQuery

Or

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

As jQuery suggests:

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

like image 192
ngen Avatar answered Sep 26 '22 13:09

ngen