form表单重置、清空方法记录

首先:contact-form 是form的id属性值

方法一:调用reset()方法

document.getElementById("contact-form")[0].reset();

注意:网上说用document.getElementById("myform").reset();可以重置的,实际上并不能清空表单内容,因为用document.getElementById()或者document.getElementByClassName()得到的是数组。原因就是我们每次通过jQuery选择器得到的都是数组。而通过document.getElementById("myform")[0];得到的是对象。对象才能调用方法。

另外注意:这种方式虽然可以重置表单,但是不能重置隐藏字段。隐藏字段要单独处理。

方法二:逐个清空input,selected的值

function resetAll() {
        $(".contact-form").find('input[type=text],select,input[type=hidden]').each(function() {
            $(this).val('');
        });
    }

方法三:排除法清空form表单

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>form表单重置</title>
    <script src="../js/jquery.min.js"></script>
</head>
<body>
    <form action="" method="post" class="contact-form">
        <label for="name">姓名:</label>
        <input type="text" name="name" id="name" value="" placeholder="请输入名字"/>
        <label>性别:</label>
        <input type="radio" name="sex" checked value=""/>男
        <input type="radio" name="sex" value=""/>女
    </form>
    <input type="button" name="" value="重置" onclick="resetForm()"/>
    
    <script type="text/javascript">
        function resetForm() {
            $(':input', '.contact-form')
                .not(':button, :submit, :reset, :hidden,:radio') // 去除不需要重置的input类型
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/no8g/p/13415552.html