스크립트를 이용하여 AJAX처리를 하다보면 Form 데이터들을 추출해야할때가 있다.
물론 각각 뽑아서 써도 되지만, 소스코드 몇타를 더 쳐야하는 불편함이 있는데 나같은 경우 타이핑하는걸 정말 귀찮아 하기 때문에 최소한으로 타이핑을 할 수 있는걸 찾아서 쓰곤한다.
아래는 serializeObject 메소드 예제이니 참고하여 사용하면 된다.
$.fn.serializeObject = function () {
let result = {};
let serializeArray;
try{
if( $(this)[0].nodeName == 'FORM'){ serializeArray = this.serializeArray();}
else{ serializeArray = $(this)[0].children; }
}catch(e){ return result; }
$.each(serializeArray,function(i,e){
try{
let node = result[e.name];
if ( (e.type == 'checkbox' || e.type == 'radio') && e.checked !== true ){ return true;}
if (typeof node !== 'undefined' && node !== null) {
if ($.isArray(node)) { node.push(e.value);}
else {result[e.name] = [node, e.value];}
}
else {result[e.name] = e.value;}
}catch(e){}
});
return result;
};
<form class="formTest" style="display:none;">
<input type="hidden" name="hidden1" value="hidden1">
<input type="hidden" name="hidden2" value="hidden2">
<input type="hidden" name="hidden[33]" value="hidden[33]">
<input type="radio" name="radio" checked value="radio1">
<input type="radio" name="radio" value="radio2">
<input type="checkbox" name="checkbox1" checked value="checkbox1">
<input type="checkbox" name="checkbox2" checked value="checkbox2">
<input type="checkbox" name="checkbox3" value="checkbox3">
<textarea name="textarea">textarea</textarea>
</form>
<div class="divTest" style="display:none;">
<input type="hidden" name="hidden1" value="hidden1">
<input type="hidden" name="hidden2" value="hidden2">
<input type="hidden" name="hidden[33]" value="hidden[33]">
<input type="radio" name="radio" checked value="radio1">
<input type="radio" name="radio" value="radio2">
<input type="checkbox" name="checkbox1" checked value="checkbox1">
<input type="checkbox" name="checkbox2" checked value="checkbox2">
<input type="checkbox" name="checkbox3" value="checkbox3">
<textarea name="textarea">textarea</textarea>
</div>
<script>
let formTest = $('.formTest').serializeObject();
let divTest = $('.divTest').serializeObject();
console.log(formTest);
/*
checkbox1: "checkbox1"
checkbox2: "checkbox2"
hidden1: "hidden1"
hidden2: "hidden2"
hidden[33]: "hidden[33]"
radio: "radio1"
textarea: "textarea"
*/
console.log(divTest);
/*
checkbox1: "checkbox1"
checkbox2: "checkbox2"
hidden1: "hidden1"
hidden2: "hidden2"
hidden[33]: "hidden[33]"
radio: "radio1"
textarea: "textarea"
*/
</script>