Mark John
Mark John

Reputation: 51

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":"[email protected]}

   {"cc":"[email protected]}

   {"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!

Upvotes: 0

Views: 464

Answers (2)

Ryker
Ryker

Reputation: 802

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":"[email protected]",
                                              "cc":"[email protected]",
                                              "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});
}

Upvotes: 1

ajai Jothi
ajai Jothi

Reputation: 2294

with Array.prototype.reducer,

function send() {
    const payload = ['to', 'cc', 'subj', 'compose'].reduce((acc, el) => {
        acc[el] = $(`#${el}`).val();

        return acc;
    }, {});

    console.log(payload);
}

Upvotes: 0

Related Questions