jQuery 表單數(shù)據(jù)存入 JSON

表單數(shù)據(jù)轉(zhuǎn)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>

調(diào)試

因為本人沒用過jQuery,所以前期寫了一堆事件,做了一些調(diào)試工作...

// 獲取需要的元素
$("#getEveryOne").click(function(){
    // 拿到form節(jié)點內(nèi)的所有元素
    $("form").children("[name]").each(function(){
        // 下面取消對應(yīng)的注釋以查看相應(yīng)效果
        // console.log(this) // DOM對象
        console.log($(this)) // jQuery對象
    })
})
  • 獲取表單中的數(shù)據(jù)
// get value
$("#getValue").click(function(){
    // 拿出text框里的內(nèi)容
    $("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"))
    })
})

表單數(shù)據(jù)存入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)
})
  • 開始把數(shù)據(jù)存入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)
})
  • 清空表單數(shù)據(jù)
// set Form
$("#setForm").click(function(){
    // 判斷當前對象是否是文本框
    $("form").children("[name]").each(function(){
        if($(this).attr("type") != "text"){
            $(this).prop("checked", false)
        }else{
            $(this).val("")
        }
    })
})
  • 把JSON數(shù)據(jù)填充進表單中
$("#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")]))
    })
})

優(yōu)化

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, " "))
    })
})

網(wǎng)頁

...

注意:

radiocheckbox 中的 value 不止一個。

若要把多個數(shù)據(jù)填充給一個 key ,是需要使用數(shù)組存放數(shù)據(jù)的。

第一次寫的時候沒考慮到 radiocheckbox 的數(shù)據(jù),就直接使用字符串賦值了。

后來調(diào)試的時候發(fā)現(xiàn),不管多選框中選擇多少個項,hobbyvalue 始終是最后一個 checkboxvalue....

使用數(shù)組,首先就要初始化對象。

因為使用 Array 對象的 push() 方法可以很方便的向后插入數(shù)據(jù)...

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML標準。 注意:講述HT...
    kismetajun閱讀 28,826評論 1 45
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,616評論 19 139
  • 以前以為愛就是對方要無條件的聽我的話,有半點不合心便覺得對方不愛我了?,F(xiàn)在才明白,愛是彼此包容,理解。
    郭snownwei閱讀 151評論 1 1
  • 作者:赤羽雄二 01 把感受寫在紙上 我試過在心情不好的時候,把對對方的疑問以及質(zhì)問寫在紙上,質(zhì)問對方為什么這樣子...
    卓安安閱讀 158評論 0 3

友情鏈接更多精彩內(nèi)容