jQuery 表单数据存入 JSON

表单数据转JSON

jQuery 1.8.3

javaScript

HTML

JSON

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <form action="">
        username <input type="text" name="username" value="hanhuoer"><br>
        password <input type="text" name="password" value="admin"><br>
        youremail <input type="text" name="email" value="hanhuoer@admin.com"><br>
        sex <input type="radio" name="sex" value="0" checked="true">男
            <input type="radio" name="sex" value="1">女<br>
        hobby <input type="checkbox" name="hobby" value="yd" checked="true"> 运动 
            <input type="checkbox" name="hobby" value="lt"> 聊天 
            <input type="checkbox" name="hobby" value="yx"> 游戏 <br>
        province <select name="province">
            <option value="hen">河南省</option>
            <option value="heb">河北省</option>
            <option value="hun">湖南省</option>
            <option value="hub">湖北省</option>
        </select>
    </form>
    <input type="button" name="" id="getEveryOne" value="getEveryOne" />
    <input type="button" name="" id="getValue" value="getValue" />
    <input type="button" name="" id="getName" value="getName" />
    <input type="button" name="" id="getType" value="getType" />
    <input type="button" name="" id="getNullJSON" value="getNullJSON" />
    <input type="button" name="" id="getJSON" value="getJSON" />
    <input type="button" name="" id="setForm" value="setForm" />
    <input type="button" name="" id="fillForm" value="fillForm" />
</body>
</html>

调试

因为本人没用过jQuery,所以前期写了一堆事件,做了一些调试工作...

// 获取需要的元素
$("#getEveryOne").click(function(){
    // 拿到form节点内的所有元素
    $("form").children("[name]").each(function(){
        // 下面取消对应的注释以查看相应效果
        // console.log(this) // DOM对象
        console.log($(this)) // jQuery对象
    })
})
  • 获取表单中的数据
// get value
$("#getValue").click(function(){
    // 拿出text框里的内容
    $("form").children("[type='text']").each(function(){
        console.log($(this).val())
    })

    console.log($("form").children("[type='radio']:checked").val())

    $("form").children("[type='checkbox']:checked").each(function(){
        console.log($(this).val())
    })

    console.log($("form").children("select").val())
})
  • 获取表单中各元素的name

后边要使用到 name 做判断

// get name
$("#getName").click(function(){
    $("form").children("[name]").each(function(){
        console.log(this.name)
    })
})
  • 获取表单中个元素的type
$("#getType").click(function(){
    $("form").children("[name]").each(function(){
        console.log($(this).attr("type"))
    })
})

表单数据存入JSON

  • 初始化JSON对象
$("#getNullJSON").click(function(){
    $("form").children("[name]").each(function(){
        if($(this).attr("type") == "text"){
            //pass
            json[$(this).attr("name")] = ""
        }else if($(this).attr("type") == "radio"){
            //pass
            json[$(this).attr("name")] = []
        }else if($(this).attr("type") == "checkbox"){
            //pass
            json[$(this).attr("name")] = []
        }else{
            json[$(this).attr("name")] = ""
        }
    })
    console.log(json)
})
  • 开始把数据存入JSON
$("#getJSON").click(function(){
    $("form").children("[name]").each(function(){
        if($(this).attr("type") == "radio"){
            if($(this).prop("checked")){
                json[$(this).attr("name")].push($(this).val())
            }
        }else if($(this).attr("type") == "checkbox"){
            if($(this).prop("checked")){
                json[$(this).attr("name")].push($(this).val())
            }
        }else{
            json[$(this).attr("name")] = $(this).val()
        }
    })
    console.log(json)
})
  • 清空表单数据
// set Form
$("#setForm").click(function(){
    // 判断当前对象是否是文本框
    $("form").children("[name]").each(function(){
        if($(this).attr("type") != "text"){
            $(this).prop("checked", false)
        }else{
            $(this).val("")
        }
    })
})
  • 把JSON数据填充进表单中
$("#fillForm").click(function(){
    $("form").children("[name]").each(function(){
        $(this).val(json[$(this).attr("name")])
        // console.log($(this))
        // console.log(json[$(this).attr("name")])
        // console.log($(this).val(json[$(this).attr("name")]))
    })
})

优化

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
        #output{
            width: 500px;
            height: 200px;
        }
    </style>
</head>
<body>
    <form action="">
        username <input type="text" name="username" value="hanhuoer"><br>
        password <input type="text" name="password" value="admin"><br>
        youremail <input type="text" name="email" value="hanhuoer@admin.com"><br>
        sex <input type="radio" name="sex" value="0" checked="true">男
            <input type="radio" name="sex" value="1">女<br>
        hobby <input type="checkbox" name="hobby" value="yd" checked="true"> 运动 
            <input type="checkbox" name="hobby" value="lt"> 聊天 
            <input type="checkbox" name="hobby" value="yx"> 游戏 <br>
        province <select name="province">
            <option value="hen">河南省</option>
            <option value="heb">河北省</option>
            <option value="hun">湖南省</option>
            <option value="hub">湖北省</option>
        </select>
    </form>
    <input type="button" name="" id="getJSON" value="getJSON" />
    <input type="button" name="" id="setForm" value="setForm" />
    <input type="button" name="" id="fillForm" value="fillForm" /><br>
    <textarea id="output"></textarea>
</body>
</html>

JS

var json = {}

function initJSON(){
    json = {}
    $("form > [name]").each(function(){
        let type = $(this).attr("type")
        let key = $(this).attr("name")
        type == "radio" || type == "checkbox" ? json[key] = [] : json[key] = "";
    })
    console.log(json)
}

$(function(){
    $("#getJSON").click(function(){
        initJSON()
        $("form > [name]").each(function(){
            let type = $(this).attr("type")
            let key = $(this).attr("name")
            let value = $(this).val()
            type == "radio" || type == "checkbox" ? $(this).prop("checked") ? json[key].push(value) : false : json[key] = value;
        })
        console.log(json)
        $("#output").val(JSON.stringify(json, null, " "))
    })
})

网页

...

注意:

radiocheckbox 中的 value 不止一个。

若要把多个数据填充给一个 key ,是需要使用数组存放数据的。

第一次写的时候没考虑到 radiocheckbox 的数据,就直接使用字符串赋值了。

后来调试的时候发现,不管多选框中选择多少个项,hobbyvalue 始终是最后一个 checkboxvalue....

使用数组,首先就要初始化对象。

因为使用 Array 对象的 push() 方法可以很方便的向后插入数据...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,824评论 1 45
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,080评论 19 139
  • 以前以为爱就是对方要无条件的听我的话,有半点不合心便觉得对方不爱我了。现在才明白,爱是彼此包容,理解。
    郭snownwei阅读 133评论 1 1
  • 作者:赤羽雄二 01 把感受写在纸上 我试过在心情不好的时候,把对对方的疑问以及质问写在纸上,质问对方为什么这样子...
    卓安安阅读 137评论 0 3