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.
var user = $('span input').serialize();
Furthermore, .serialize() gives you a string result, not an object.
Perhaps you wanted this instead:
var username = $('span input[name=username]').val();
If you want an object that references all the values, you'll need to make it.
var vals = {};
$('span input').each(function() {
vals[this.name] = this.value;
});
var name = vals.username;
You don't need serialize here.
What you need is to get the value of the input whose name is "username" :
alert($('input[name="username"]').val());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With