I’ve got the following code.
JavaScript
<script>
function postUser() {
var user = $('span input').serialize;
alert(user.username);
}
</script>
HTML
<span>
User name : <input type="text" name="username"><br />
Password: <input type="password" name="password" /><br />
First name: <input type="text" name="firstName" /><br />
Last name: <input type="text" name="lastName" /><br />
<button onclick="postUser()">Submit</button>
</span>
When I populate the items in the UI, the alert says “undefined” – but I thought by serializing the array it should be a JSON object? Any ideas why username is undefined?
You forgot the
()in order to call the function.Furthermore,
.serialize()gives you astringresult, not an object.Perhaps you wanted this instead:
If you want an object that references all the values, you’ll need to make it.