본문 바로가기
JavaScript

serialize form

by SSaMKJ 2013. 4. 23.

jQuery를 사용 할 수 없을 때 javascript에서 form 태그를 serialize해서 form 태그 내의 name속성을 가지는 태그들의 값을 가지고 올 때 사용한다.

	/**
	IE 에서는 obj.serialize() function이 동작하지 않기 때문에 아래와 같이 만들어 준다.
	*/
	function serialize(form)
	{
	    if (!form || form.nodeName !== "FORM") {
	            return;
	    }
	    var i, j, q = [];
	    for (i = form.elements.length - 1; i >= 0; i = i - 1) {
	            if (form.elements[i].name === "") {
	                    continue;
	            }
	            if (form.elements[i].disabled === true) {
	                continue;
	        	}
	            switch (form.elements[i].nodeName) {
	            case 'INPUT':
	                    switch (form.elements[i].type) {
	                    case 'text':
	                    case 'hidden':
	                    case 'password':
	                    case 'button':
	                    case 'reset':
	                    case 'submit':
	                            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	                            break;
	                    case 'checkbox':
	                    case 'radio':
	                            if (form.elements[i].checked) {
	                                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	                            }                                               
	                            break;
	                    }
	                    break;
	                    case 'file':
	                    break; 
	            case 'TEXTAREA':
	                    q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	                    break;
	            case 'SELECT':
	                    switch (form.elements[i].type) {
	                    case 'select-one':
	                            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	                            break;
	                    case 'select-multiple':
	                            for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
	                                    if (form.elements[i].options[j].selected) {
	                                            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
	                                    }
	                            }
	                            break;
	                    }
	                    break;
	            case 'BUTTON':
	                    switch (form.elements[i].type) {
	                    case 'reset':
	                    case 'submit':
	                    case 'button':
	                            q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
	                            break;
	                    }
	                    break;
	            }
	    }
	    return q.join("&");
	}


댓글