Clear form fields with jQuery

2019-01-01 04:42发布

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?

27条回答
倾城一夜雪
2楼-- · 2019-01-01 05:03

If i want to clear all the fields except accountType..Use the following

$q(':input','#myform').not('#accountType').val('').removeAttr('checked').removeAttr('selected');
查看更多
临风纵饮
3楼-- · 2019-01-01 05:04

I got easiest trick to reset form

jQuery("#review-form")[0].reset();

or

$("#review-form").get().reset();
查看更多
长期被迫恋爱
4楼-- · 2019-01-01 05:04

With Javascript you can simply do it with this syntax getElementById("your-form-id").reset();

you can also use jquery by calling the reset function this way $('#your-form-id')[0].reset();

Remember not to forget [0]. You will get the following error if

TypeError: $(...).reset is not a function

JQuery also provides an event you can use

$('#form_id').trigger("reset");

I tried and it works.

Note: Its important to notice that these methods only reset your form to their initial value set by the server on page load. This means if your input was set on the value 'set value' before you did a random change, the field will be reset to that same value after reset method is called.

Hope it helps

查看更多
零度萤火
5楼-- · 2019-01-01 05:04

the code I see here and on related SO questions seems incomplete.

Resetting a form means setting the original values from the HTML, so I put this together for a little project I was doing based on the above code:

            $(':input', this)
                .not(':button, :submit, :reset, :hidden')
                .each(function(i,e) {
                    $(e).val($(e).attr('value') || '')
                        .prop('checked',  false)
                        .prop('selected', false)
                })

            $('option[selected]', this).prop('selected', true)
            $('input[checked]',   this).prop('checked',  true)
            $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })

Please let me know if I'm missing anything or anything can be improved.

查看更多
泪湿衣
6楼-- · 2019-01-01 05:06

If someone is still reading this thread, here is the simplest solution using not jQuery, but plain JavaScript. If your input fields are inside a form, there is a simple JavaScript reset command:

document.getElementById("myform").reset();

More about it here: http://www.w3schools.com/jsref/met_form_reset.asp

Cheers!

查看更多
永恒的永恒
7楼-- · 2019-01-01 05:08

Simple but works like a charm.

$("#form").trigger('reset'); //jquery
document.getElementById("myform").reset(); //native JS
查看更多
登录 后发表回答