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:14

The following code clear all the form and it's fields will be empty. If you want to clear only a particular form if the page is having more than one form, please mention the id or class of the form

$("body").find('form').find('input,  textarea').val('');
查看更多
临风纵饮
3楼-- · 2019-01-01 05:15
$('#editPOIForm').each(function(){ 
    this.reset();
});

where editPOIForm is the id attribute of your form.

查看更多
其实,你不懂
4楼-- · 2019-01-01 05:16

Why does it need to be done with any JavaScript at all?

<form>
    <!-- snip -->
    <input type="reset" value="Reset"/>
</form>

http://www.w3.org/TR/html5/the-input-element.html#attr-input-type-keywords


Tried that one first, it won't clear fields with default values.

Here's a way to do it with jQuery, then:

$('.reset').on('click', function() {
    $(this).closest('form').find('input[type=text], textarea').val('');
});
查看更多
像晚风撩人
5楼-- · 2019-01-01 05:16

Add hidden reset button as follows

<input id="resetBtn" type="reset" value="reset" style="display:none" />
// Call reset buttons click event
// Similar to ClearInputs('resetBtn');
function ClearInputs(btnSelector) {
     var btn = $("#" + btnSelector);
     btn.click();
}
查看更多
其实,你不懂
6楼-- · 2019-01-01 05:19
$('form[name="myform"]')[0].reset();
查看更多
听够珍惜
7楼-- · 2019-01-01 05:20

Why you dont use document.getElementById("myId").reset(); ? this is the simple and pretty

查看更多
登录 后发表回答