Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this JSON variable undefined? [closed]

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?

like image 455
david99world Avatar asked Jun 27 '26 23:06

david99world


2 Answers

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;
like image 142
I Hate Lazy Avatar answered Jun 30 '26 11:06

I Hate Lazy


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());
like image 40
Denys Séguret Avatar answered Jun 30 '26 11:06

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!