Hendrik Human
Hendrik Human

Reputation: 135

JSON object does not want to initialize

Hello I am trying to create a JSON object using some values I take from a form. For some reson the code isn't working. I triple checked all the names f the inputs so you can assume they are correct. I did isolate the problem to the line where I instantiate my JSON object:

    function createJSON()
    {
        if (document.forms["formIn"]["gender"][0].checked == true)
        {
            var g= "male";
        }
        else if (document.forms["formIn"]["gender"][1].checked == true)
        {
            var g= "male";
        }
        var jsonobj={"name":document.forms["formIn"]["name"].value, "surname":document.forms["formIn"]["surname"].value, "email":document.forms["formIn"]["email"], "dob":document.forms["formIn"]["dob"].value, "password":document.forms["formIn"]["password"].value, "cpassword":document.forms["formIn"]["confirm_password"].value, "gender":g}
        var jsonstr=JSON.stringify(jsonobj);
        alert(jsonstr);
        var newjobj=JSON.parse(jsonstr);
        alert(newjobj.email);
    }

Thanks for everyones help. I just didn't have a .value after my email. Cleared alot of other stupid mistakes aswell, but still my second alert only says [object] [object].

Upvotes: 0

Views: 444

Answers (2)

BLSully
BLSully

Reputation: 5939

Please try this:

function createJSON()
{
    var g = "unknown",
        jsonobj,
        jsonstr,
        newjobj;

    if (document.forms["formIn"]["gender"][0].checked == true)
    {
        g = "male";
    }
    else if (document.forms["formIn"]["gender"][1].checked == true)
    {
        g = "female";
    }
    jsonobj={"name":document.forms["formIn"]["name"].value, "surname":document.forms["formIn"]["surname"].value, "email":document.forms["formIn"]["email"], "dob":document.forms["formIn"]["dob"].value, "password":document.forms["formIn"]["password"].value, "cpassword":document.forms["formIn"]["confirm_password"].value, "gender":g}
    jsonstr=JSON.stringify(jsonobj);
    alert(jsonstr);
    newjobj=JSON.parse(jsonstr);
    alert(newjobj.email);
}

Upvotes: 1

aug
aug

Reputation: 11714

You are missing a ; at the end of where you instantiate your JSON object. Everything else seems to be okay though.

Upvotes: 0

Related Questions