学弟教程-JS-JQuery操作Form

一、目的

  1. 使用Jquery获取form中所有控件值,并封装成JSON
  2. 清空form

二、代码实现

2.1 head

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <title>Document</title>
</head>

2.2 body

<body>
    <form method="post" action="" id="form">
        用户名: <input type="text" name="username"><br>
        密码: <input type="text" name="pwd"><br>
        <button type="submit" value="" id="submitForm">提交</button>
        <button type="submit" value="" id="resetForm">清空</button>
    </form>
</body>

2.3 script

<script>
    function get_form_value(){
    	//保存控件名与控件值的字典
        var d = {};
        var t = $('#form').serializeArray();
        $.each(t, function () {
            d[this.name] = this.value;
        })
        return JSON.stringify(d)
    }
	
    $('#submitForm').click(function () {
        alert(get_form_value());
    })
	$('#resetForm')click(function(){
		$('#from')[0].reset()
	}
</script>
  1. serializeArray() 方法通过序列化表单值来创建对象(name 和 value)的数组
  2. each() 对 jQuery 对象进行迭代,为每个匹配元素执行函数
  3. Jquery中没有reset方法,故此处需转成dom,再用reset,即$(’#from’)[0].reset()

三、 全部代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <title>Document</title>
</head>

<body>
    <form method="post" action="" id="form">
        用户名: <input type="text" name="username"><br>
        密码: <input type="text" name="pwd"><br>
        <button type="submit" value="" id="submit_demo">提交</button>
    </form>
</body>
<script>
    function get_form_value(){
    	//保存控件名与控件值的字典
        var d = {};
        var t = $('#form').serializeArray();
        $.each(t, function () {
            d[this.name] = this.value;
        })
        return JSON.stringify(d)
    }
	
    $('#submitForm').click(function () {
        alert(get_form_value());
    })
    
	$('#resetForm')click(function(){
		$('#from')[0].reset()
	}
</script>

</html>

猜你喜欢

转载自blog.csdn.net/qq_41452937/article/details/106415289