I am trying to create a json object from variables that I am getting in a form.
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var phone = $('#phoneNumber').val();
var address = $('#address').val();
So far I have the code below but it will not validate or work. Im new to this, please help! Changing var to this:
var jsonObject =
{
firstName: firstName,
lastName: lastName,
phoneNumber:phoneNumber,
address:address
}
in JSONlint i am getting this error:
Parse error on line 1: varjsonObject={
^ Expecting '{', '['
This question is related to
javascript
jquery
json
object
Try this to see how you can create a object from strings.
var firstName = "xx";
var lastName = "xy";
var phone = "xz";
var adress = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);
It's called on Object Literal
I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.
var formObject = {"formObject": [
{"firstName": firstName, "lastName": lastName},
{"phoneNumber": phone},
{"address": address},
]}
Although this seems to make more sense (Why do you have an array in the above literal?):
var formObject = {
firstName: firstName
...
}
You're referencing a DOM element when doing something like $('#lastName')
. That's an element with id
attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject
is in the same scope as the variable declarations) -
var formObject = {
formObject: [
{
firstName:firstName, // no need to quote variable names
lastName:lastName
},
{
phoneNumber:phoneNumber,
address:address
}
]
};
This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.
var formValues = {
firstName: $('#firstName').val(),
lastName: $('#lastName').val(),
phone: $('#phoneNumber').val(),
address: $('#address').val()
};
Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.
Source: Stackoverflow.com