views:

1544

answers:

1

Is there an easy way to store form data in a data() object after submit?

Suppose this is my form:

<form id='myform'>
<input type='text' name='bar' value='lorem'/>
<input type='text name='foo' value='ipsum'/>
</form>

After submit the data should be stored like this:

$("#myform").data('bar','lorem');
$("#myform").data('foo','ipsum');

+3  A: 

You may do something like this:

$('#myform').submit(function(e) {
    e.preventDefault(); // don't submit the form
    var form = $(this); // store it for later reference
    form.children('input').each(function() {
        form.data($(this).attr('name'), $(this).attr('value'));
    });
});

Edit: My code had some errors in it (getChildren » children, myform » #myform) – I've now corrected it.

Note that this script doesn't submit the form. You may add some nifty ajax to do that :) http://docs.jquery.com/Ajax/serialize

Update: Actually, jQuery already has this functionality built-in: form.serialize(). It returns a valid query string:

<form id="myForm">
    <input type="radio" value="A" name="foo" checked="checked" /> A<br />
    <input type="radio" value="B" name="foo" /> B
    <input type="text" name="bar" value="Bla bla" />
</form>
<script>
var queryString = $('#myForm').serialize(); //foo=A&bar=Bla+bla
</script>
moff
Peter Boughton
You're right, but I just pointed bartclaeys in the right direction (IMHO). I'll update the code soon, though.
moff
Thx Moff! Still requires a lot of code (if I want to add selects etc). Thought there was something around like SerializeToDataObject.
bart