javascripthtmljson

Converting a form input values to JSON


I've been having trouble finding information to help me learn and understand the concepts of JavaScript and JSON.

I've created an HTML document that has input for 'to', 'cc', 'subj' and a text area 'compose'.

After the user fills in the input boxes and text, the user clicks the "send" button and the information is logged in the console.

The onclick function I'm using now is:

function send() {
    var toEmail = $("#to").val();
    var ccEmail = $("#cc").val();
    var subject = $("#subj").val();
    var content = $("#compose").val();

    console.log(toEmail);
    console.log(ccEmail);
    console.log(subject);
    console.log(content);
}

When I click "send" now, the information is logged like:

Current:

I want the console to show:

   {"to":"test_email@hotmail.com}

   {"cc":"ccEmail@hotmail.com}

   {"subj":"Testing"}

   {"compose":"Send to console"}

I know this is likely very basic. However, I am struggling to grasp JSON when working with user input.

Thanks!


Solution

  • You may wrap the output in an object. Then you can use JSON.stringify to change the object into a JSON (string).

    function send() {
        var toEmail = $("#to").val();
        var ccEmail = $("#cc").val();
        var subject = $("#subj").val();
        var content = $("#compose").val();
    
        var result = {
            to: toEmail,
            cc: ccEmail,
            subj: subject,
            compose: content
        };
        console.log(JSON.stringify(result));   /*{"to":"test_email@hotmail.com",
                                                  "cc":"ccEmail@hotmail.com",
                                                  "subj":"Testing",
                                                  "compose":"Send to console"} */
        return JSON.stringify(result);
    }
    

    For all individual strings you may do:

    function send() {
        var toEmail = $("#to").val();
        var ccEmail = $("#cc").val();
        var subject = $("#subj").val();
        var content = $("#compose").val();
    
        console.log(JSON.stringify({to: toEmail});
        console.log(JSON.stringify({cc: ccEmail});
        console.log(JSON.stringify({subj: subject});
        console.log(JSON.stringify({compose: content});
    }