반응형
핵심 함수
<script>
function getFormJson() {
// Select Form
let selForm = document.querySelector("#basic_form");
// Getting an FormData
let data = new FormData(selForm);
// Getting a Serialize Data from FormData
let serializedFormData = serialize(data);
// Log
console.log(JSON.stringify(serializedFormData));
}
function serialize (rawData) {
let rtnData = {};
for (let [key, value] of rawData) {
let sel = document.querySelectorAll("[name=" + key + "]");
// Array Values
if (sel.length > 1) {
if (rtnData[key] === undefined) {
rtnData[key] = [];
}
rtnData[key].push(value);
}
// Other
else {
rtnData[key] = value;
}
}
return rtnData;
}
</script>
Test.html
<!DOCTYPE html>
<html>
<head>
<title>Test Serialize Form</title>
<style>
body {
background-color: #005858;
color: whitesmoke;
}
div {
width: 100%;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
span {
width: 100%;
}
input[type="checkbox"] {
width: 50px;
}
input[type="text"], textarea {
width: 100%;
height: 30px;
padding: 0;
margin-bottom: 5px;
display: block;
outline: none;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
textarea {
width: 100%;
height: 500px;
font-size: 16px;
}
label {
font-weight: bold;
}
</style>
<script>
function btnClick() {
// Select Form
let selForm = document.querySelector("#basic_form");
// Getting an FormData
let data = new FormData(selForm);
// Getting a Serialize Data from FormData
let serializedFormData = serialize(data);
// Setting a Temp Data to Textarea
document.querySelector("#txtarea_json").innerText = JSON.stringify(serializedFormData);
}
function serialize (rawData) {
let rtnData = {};
for (let [key, value] of rawData) {
let sel = document.querySelectorAll("[name=" + key + "]");
// Array Values
if (sel.length > 1) {
if (rtnData[key] === undefined) {
rtnData[key] = [];
}
rtnData[key].push(value);
}
// Other
else {
rtnData[key] = value;
}
}
return rtnData;
}
</script>
</head>
<body>
<form action="/" id="basic_form">
<div>
<label for="text">Name</label>
<input type="text" name="name">
</div>
<label>Favorite Food Style</label>
<div>
<label><input type="checkbox" name="chkFood" value="Korean">Korean Style</label><br>
<label><input type="checkbox" name="chkFood" value="Italian">Italian Style</label><br>
<label><input type="checkbox" name="chkFood" value="American">American Style</label><br>
<label><input type="checkbox" name="chkFood" value="Mexican">Mexican Style</label><br>
</div>
</form>
<button onclick="btnClick()">Show Temp Json</button>
<textarea id="txtarea_json">
</textarea>
</body>
</html>
반응형
'프론트엔드 > Java Script, jQuery, AJAX' 카테고리의 다른 글
기본 JSON 객체로 정렬 / Beatifier / Beatify / formatter 하기 (0) | 2019.05.08 |
---|---|
jquery 1.12 - jqgrid 5.3.1 - bootstrap 4 설정하기 (0) | 2018.05.25 |
아이폰 / 아이패드 / IOS / 사파리 팝업 문제 해결 (0) | 2018.02.26 |
Jqeury GET 방식일 때 쓰는 param을 쉽게 만들기 $.param (0) | 2017.04.06 |
[JavaScript] HTML 테이블 동적 Rowspan (0) | 2016.10.23 |
WRITTEN BY
,