I have 5 select tags in a page (user can select number max 10 only). I want to fill this select boxes with dynamic data. I wrote a function for this.
This function called on a radio button clicked. Data send to a PHP page and return back result to javascript function.

function getProject()
{   
    $.ajax({
        type: "POST",
        url: "custompage.php",
        dataType: "json",
        data: { 'projectid': projectid },
        cache:false,
        success:
          function(data){
            for (var i = 0; i < data.length; i++)
            {
                var detail = String(data[i]);
                var strSplit = detail.split(",");               
                var option = new Option(strSplit[1], strSplit[0]);
                var firstvalue = new Option('Please Select', '');
                for(var j=1; j<10; j++)
                {
                    var controlid = '#x'+j+'_sale_order_no';
                    $('option',controlid).remove();
                    if ($('#x'+j+'_sale_order_no').length)        //check if an id exists in the page or not                                        $('#x'+j+'_sale_order_no').append($(firstvalue));                   
                }
                for(var k=1; k<10; k++)
                {
                    if ($('#x'+k+'_sale_order_no').length)                  
                        $('#x'+k+'_sale_order_no').append($(option));                   
                }
            }
        }
    });
}

But after execution of this function, last select box only contains values and others having empty option list.
What is the problem in above code.

I combined two for loops and solved the issue.

function(data){
    for(var flag = 1; flag <= 10; flag++)
    {
        for (var i = 0; i <= data.length; i++)
        {
            if(i == 0){
                $("#x"+flag+"_sale_order_no").empty();
                var firstoption = new Option("Please Select","");
                $("#x"+flag+"_sale_order_no").append($(firstoption));
                if(data.length > 0){
                    var detail = String(data[i]);
                    var strSplit = detail.split(",");
                    var option = new Option(strSplit[1], strSplit[0]);
                    $("#x"+flag+"_sale_order_no").append($(option));
                }
            }
            else if(i < data.length){
                if(data.length > 0){
                var detail = String(data[i]);
                var strSplit = detail.split(",");
                var option = new Option(strSplit[1], strSplit[0]);
                $("#x"+flag+"_sale_order_no").append($(option));
                }
            }
            else{   }
        }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.