Is there a way to do this only using javascript? thank you!
4 Answers
Basic JavaScript...
var arr = document.forms[0].elements;
for (var i = 0; i < arr.length; i++) {
var el = arr[i];
// do something with it.
console.log(el.value) // or similar
}
You might take a look at jQuery.serialize()
It gives back a standard URL-encoded string. However the nice thing is that it encapsulates getting the values of all of the different types of form elements.
4 Comments
josh.trow
I would normally downvote the use of jQuery when the question says
only using Javascript, but I don't think the OP knows the difference :)Mark Biek
The requirements were vague enough, I figured jQuery-based solutions were reasonable :)
RobG
jQuery wasn't asked for, nor was serialisation, and there already is a good solution. But no downvote, I'm not that mean. :-)
Alexei Levenkov
If you go down the route of "pure JavaScript" - you can't do what OP asks for as JavaScript itself does not include DOM objects... JQuery looks as pure JavaScript as it can get in browser - no C#, VBScript, PHP, LISP,... :)
Have a look at this. These guys built something that only uses pure JS and serializes a form.
Comments
This function returns all form elements as in an associative array. It also returns all values for multiple input elements that are selected.
function getFormVals(form) {
var values = [];
for(var i = 0, len = form.elements.length; i < len; i++) {
var input = form.elements[i];
switch (input.type.toLowerCase()) {
case "checkbox":
values[input.name] = values[input.name] || [];
if (input.checked) {
values[input.name].push(input.value);
}
break;
case "radio":
values[input.name] = values[input.name] || "";
if (input.checked) {
values[input.name] = input.value;
}
break;
case "select-multiple":
values[input.name] = values[input.name] || [];
for (var i = 0, len = input.length; i < len; i++) {
if (input[i].selected) {
values[input.name].push(input[i].value);
}
}
break;
default:
values[input.name] = input.value;
break;
}
}
return values;
}
usage could be:
<form onsubmit="var vals = getFormVals(this); alert(vals['myinput']);" >
<input type="checkbox" name="myinput" value="ckbx1" />
<input type="checkbox" name="myinput" value="ckbx2" />
<input type="submit" />
</form>