The serialize()
method is designed to create a URL encoded string, usually used for AJAX requests to the server. This means you can't access the string like an object or array in the traditional sense, instead you have two options for achieving the result you want...
(This question might be old but the original answers don't really answer the initial question and nor do they give much explanation...)
Method 1 : Serialize Array
The first method and my preferred one, is to use the serializeArray()
method, this can be a useful method if you have several values and want to get the value of each, rather than having to explicitly select each element to get there value.
A solution, like below, using this method will serialize the selected form or element into an array of objects which can then be put into a single object and accessed easily using a function to get the values when and where you need them in your script...
//Serialize the Form
var values = {};
$.each($("form").serializeArray(), function (i, field) {
values[field.name] = field.value;
});
//Value Retrieval Function
var getValue = function (valueName) {
return values[valueName];
};
//Retrieve the Values
var url = getValue("url");
Here's a JSFiddle Code Snippet...
$(document).ready(function () {
var values = {};
$.each($("form").serializeArray(), function (i, field) {
values[field.name] = field.value;
});
var getValue = function (valueName) {
return values[valueName];
};
var first = getValue("FirstName");
var last = getValue("LastName");
$("#results").append(first + " & ");
$("#results").append(last);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="">
First name:
<input type="text" name="FirstName" value="Foo" />
<br>Last name:
<input type="text" name="LastName" value="Bar" />
<br>
</form>
<div id="results"></div>
Method 2 : Element Value
The second method, as already mentioned is to simply get the value directly from the form element that you are trying to collect, rather than serialising the value. This can simply be achieve using the jQuery val()
method - this will get the entered value of the selector.
While this method is simple for selecting a single element, it can quickly become messy when trying to select and retrieve the value of several elements from a form...
$("input").val();