HTML Form to JSON

This code example demonstrates how you can use a form to collect input and output in a json format. The way this example works is excellent because it works dynamically, the inputs of your form are the names of the attributes stored in JSON, if a field is blank then this is setup to not insert that field in the JSON. This currently only supports the text form input, but I am planning to add other inputs to this script as well such as checkboxes, radio buttons, and more.

by Luke Gackle

HTML

<form id="data" onsubmit="return make_json(this); return false;" method="post">
First name: <input type="text" name="first"/><br>
Last name: <input type="text" name="last"/><br>


<input type="button" id="button1" value="Format"/>
</form>

<pre id="output">
</pre>

JavaScript

//Submit button did not want to work with jsfiddle so this is the workaround, using JS to set onclick event
document.getElementById("button1").onclick = function(e){
make_json(document.getElementById("data"));
}


function make_json(form){
    var json={};
    
    var elements = form.elements;
    
    for (var i = 0, element; element = elements[i++];) {
    if (element.type == "text" && element.value != ""){
        json[element.name] = element.value;
        }
    }
    
    var html = JSON.stringify(json,null,4);
    document.getElementById('output').innerHTML=html;
    return false;
}