Hasan Bozok Hasan Bozok - 1 year ago 61
JSON Question

How to access html elements and store them in a json text with javascript

Consider an html form which includes some form elements like labels, select boxes radio buttons etc. With the help of javascript i want to store child elements of that form in a json string like this:

{
"label": {
"content": "This is a label"
},

"textbox",

},

"checkbox": {
"option": "Option 1",
"option": "Option 2",
"option": "Option 3"
},

"select": {
"option": "Option 1",
"option": "Option 2"
}


Do you know how can achieve this? Are there any code samples that i can get inspired?

Answer Source

You can do like following :

function setAllElements() {

    var inputElements = document.getElementsByTagName('input');
    var selectElements = document.getElementsByTagName('select');
    var jsonObj = {};


    //Handling of all inputs
    for (i = 0; i < inputElements.length; i++) {
        if (inputElements[i].type == "text")
            jsonObj[inputElements[i].type+i] = inputElements[i].value;
    }

    //Handling of all select
    for (i = 0; i < selectElements.length; i++) {
        jsonObj[selectElements[i].type+i] = selectElements[i].value;
    }

    console.log(jsonObj);

}

HTML :

<input type="text" value="Text first">
<select id="e">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
<select>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

<input type="button" onclick="setAllElements();" value="Click me!!">

If you want JSON Object then key cannot be same ,so i have put like number of the element like if you have 5 input type="text" then it will give you text0,text1,text2,text3,text4 with their corresponding values.

 {
        text0: "sdfdsf", 
        select-one0: "A", 
        select-one1: "A"
    }

Similarly you can extend this function by adding support for all the elements (like textarea, button etc.)that you are using in your page.

Hope it help you !!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download