views:

40

answers:

3

Is there a simple, one-command way to get the data of a form as it would be if it was to be submitted in the classic HTML-only way?

For example, in:

<form>
 <input type="radio" name="foo" value="1" checked="checked" />
 <input type="radio" name="foo" value="0" />
 <input name="bar" value="xxx" />
 <select name="this">
  <option value="hi" selected="selected">Hi</option>
  <option value="ho">Ho</option>
</form>

Out:

{
 "foo": "1",
 "bar": "xxx",
 "this": "hi"
}

Something like this is too simple, since it does not (correctly) include textareas, selects, radio buttons and checkboxes:

$("#form input").each(function() {
 data[theFieldName] = theFieldValue;
});
A: 
$("#form input, #form select, #form textarea").each(function() {
 data[theFieldName] = theFieldValue;
});

other than that, you might want to look at serialize();

pixeline
+2  A: 

$('form').serialize()

chelmertz
Close, but perhaps something that returns an array with key-value pairs instead of a single string?
Bart van Heukelom
Nvm, found it in the comments for the serialize() function. It's called serializeArray. It returns an array of arrays (which contain an entry "name" and "value") but that should be easy enough to transform.
Bart van Heukelom
@second comment: great, I didn't even know that :)
chelmertz
A: 
$('#myform').serialize();
Andy Baird