Clear form fields with jQuery

前端 未结 30 2707
甜味超标
甜味超标 2020-11-22 15:48

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         


        
30条回答
  •  有刺的猬
    2020-11-22 16:28

    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.

提交回复
热议问题