Created
December 26, 2011 05:19
-
-
Save ahomu/1520561 to your computer and use it in GitHub Desktop.
フォームの入力値をobjectとして取得するよ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* フォーム内の入力値をobjectとして取得する | |
* | |
* @param {Node} form | |
* @return {Object} | |
*/ | |
function getFormData(form) { | |
if (form.tagName !== 'FORM') { | |
throw new TypeError('Argument must be HTMLFormElement.'); | |
} | |
var elms = toArray(form.elements), | |
e, i, pos, isAry, name, val, rv = {}, | |
list = [], li, | |
option, j, jz; | |
// form.elementsに,INPUT[type="image"]要素は含まれない | |
if (form.innerHTML.indexOf('type="image"') || form.innerHTML.indexOf("type='image'")) { | |
list = toArray(form.getElementsByTagName('input')); | |
i = 0; | |
while (li = list[i++]) { | |
if (li.type === 'image') { | |
elms.push(li); | |
} | |
} | |
} | |
i = 0; | |
while (e = elms[i++]) { | |
// form.elementsに,FIELDSET要素も含まれる | |
if ( | |
e.disabled === true || | |
e.type === 'radio' && e.checked === false || | |
e.type === 'checkbox' && e.checked === false || | |
e.tagName === 'FIELDSET' || | |
0 | |
) { | |
continue; | |
} | |
pos = e.name.indexOf('['); | |
isAry = pos !== -1; | |
name = isAry ? e.name.substr(0, pos) : e.name; | |
val = e.value; | |
// multiple属性のついたSELECT要素 | |
if (e.tagName === 'SELECT' && e.multiple === true && isAry) { | |
rv[name] || (rv[name] = []); | |
j = 0; | |
jz = e.length; | |
for (; j<jz; j++) { | |
option = e[j]; | |
if (option.selected === true) { | |
rv[name].push(option.value); | |
} | |
} | |
} else if (isAry) { | |
rv[name] || (rv[name] = []); | |
rv[name].push(val); | |
} else { | |
rv[name] = val; | |
} | |
} | |
return rv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment