如何重置特定表单中的所有控件值

时间:2014-05-15 18:41:03

标签: jquery

这里我有一个重置表单控件数据的脚本,但它适用于所有表单,如果我需要重置一个特定的表单,那么我怎么能这样做

<script type="text/javascript">
        function resetFields(form) {
            $(':input', form).each(function() {
                var type = this.type;
                var tag = this.tagName.toLowerCase(); // normalize case
                // to reset the value attr of text inputs,
                // password inputs, fileUpload and textareas
                if (type == 'text' || type == 'password' || tag == 'textarea' || type=='file')
                    this.value = "";
                // checkboxes and radios need to have their checked state cleared                
                else if (type == 'checkbox' || type == 'radio')
                    this.checked = false;
                // select elements need to have their 'selectedIndex' property set to -1
                // (this works for both single and multiple select elements)
                else if (tag == 'select')
                    this.selectedIndex = 0;
            });
        }

    </script> 

在上面的脚本中进行更改。

1 个答案:

答案 0 :(得分:0)

只需在表单中添加id

即可
<form id="my_form" ...>...</form>

然后调用给定的函数传递这样的表单:

$('#reset_button').on('click', function() {
    resetFields($('#my_form'));
});

您的函数会遍历传递表单中的所有字段并重置其值。