Convert the items of an LI into a json object using jquery

by Mohammad Wali

HTML

<ul class="nameList">
    <li value="1">Bob</li>
    <li value="2">Frank</li>
    <li value="3">Sally</li>
</ul>

<!-- result container -->
<pre id="result"></pre>
<!-- result container ends -->

CSS

pre {
    word-wrap:break-word;
    padding:10px;
    margin:10px;
    background:#eee;
    line-height: 1.7
}

JavaScript

var mylist = [];

$("ul.nameList > li").each(function () {
    mylist.push({
        "id": $(this).attr("value"),
            "title": $(this).text()
    });
})

// then you can simply pass it to the post method 
$.post("myhandler.php", {list:mylist}, function (data) {
    // here you go!
})


// for result only
$("#result").html(JSON.stringify(mylist))