Converting Form Data To An Object
I don't want to post the data to a server I want to pass it into a client side function that takes an object. What is the best way to do that?
Solution 1:
You can just create your own object as such:
<form name='f1'>
<inputtype='text'name='firstname' /><inputtype='text'name='lastname' />
</form>
window.onload = function()
{
varPerson =
{
'FirstName' : document.f1.firstname.value,
'LastName' : document.f1.lastname.value
}
}
A JSON object
is just a regular Javascript object, because JSON is subset of Javascript.
Solution 2:
If you're using jQuery you may want to look at the .serializeArray() function it provides as it does all you want in a single call. Using TJ's example;
<scripttype="text/javascript">
$(function () {
$('form[name="f1"]').submit(function() {
var person = $(this).serializeArray();
// Do what you will with 'person' now...
});
});
</script><formname="f1"><inputtype="text"name="firstname" /><inputtype="text"name="lastname" /><inputtype="submit"value="Submit" /></form>
This way you don't have to manually build an object and declare a property for each field which helps avoid human error.
If for some reason you don't want to use jQuery then you could always look at the code to see the logic used and create your own function.
Post a Comment for "Converting Form Data To An Object"