jQuery: serialize a form to JSON

by Fu-Ching Hsiao

HTML

<form action="#" method="post" id='aa'>
    <div>
        <label for="name">Name</label>
        <input type="text" name="name" id="name" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email" id="email" />
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" id="password" />
        <input type="checkbox" name="chk"/>
        <input type="checkbox" name="chk" value="11"/>
        <input type="checkbox" name="chk"/>
        <input type="checkbox" name="chk"/>
    </div>
    <p>
        <input type="submit" value="Send" />
    </p>
</form>

CSS

form div {
    margin-bottom: 0.5em;
}
form div label, form div input {
    display: block;
    margin-bottom: 0.3em;
}

JavaScript

function populate(frm, data) {   
    $.each(data, function(key, value) {  
        var ctrl = $('[name='+key+']', frm);  
        switch(ctrl.prop("type")) { 
            case "radio": case "checkbox":   
                ctrl.each(function() {
                    if($(this).attr('value') == value) $(this).attr("checked",value);
                });   
                break;  
            default:
                ctrl.val(value); 
        }  
    });  
}
  var c = {
        email: "value",
        name: "value",
        password: "value",
        chk: "11"
     };
populate( $("#aa"),c);