Pages

Wednesday, April 17, 2013

Lazy loading of HTML select via Ajax

In the web application sometimes HTML select drop down holds large number of data which impact the performance of the webpage. Due large data page gets heavier. Work around to this problem is Lazy Loading of select drop down via Ajax.

Working Demo

Example: In the below example additional data is loaded on click of more via Ajax request.

<select id="mySelect" 
         onChange="updateOptionList(this.value,this.selectedIndex)">
    <option value="1">--1--</option>
    <option value="2">--2--</option>
    <option value="3">--3--</option>
    <option value="4">--4--</option>
    <option value="5">--5--</option>
    <option value="6">--6--</option>
    <option value="7">--7--</option>
    <option value="8">--8--</option>
    <option value="9">--9--</option>
    <option value="10">--10--</option>
    <option value="more">more</option>
</select> 

JavaScript:
var data = {
    json: $.toJSON({
        array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    })
}
var elmt;
var num = 1;

function updateOptionList(value, index) {
    if (value == 'more') {
        elmt = document.getElementById("mySelect");
        elmt.remove(elmt.selectedIndex);
        /*Ajax request to load data*/
        $.ajax({
            url: "/echo/json/",
            data: data,
            type: "POST",
            success: function (response) {
                $.each(response.array, function (index, value) {
                    opt = document.createElement("option");
                    opt.value = num * 10 + value;
                    opt.innerHTML = '--' + (num * 10 + value) + '--';
                    elmt.appendChild(opt);
                });
                opt1 = document.createElement("option");
                opt1.value = 'more';
                opt1.innerHTML = 'more';
                elmt.appendChild(opt1);
                num++;
            }
        });
    }
}