Billy
Billy

Reputation: 65

Show data according to the drop down menu ID

HTML and PHP

<?php for($i=0;$i<2;$i++) { ?>
<select id="name_<?php echo $i;?>">
    <option value="John">John</option>
    <option value="Alice">Alice</option>
</select>

<input type="text" id="name-id_<?php echo $i;?>">
<input type="text" id="location_<?php echo $i;?>">

<?php } ?>

JS

for (var i = 0; i < 2; i++) 
{
    $('select#name_'+i).on('change',function()  
    {
        name = $('select#name_'+i).val();
        if($.trim(name) !='')
        {
            $.post('ajax/name.php',{name:name},function(data)
            {
                $('input#name-id_'+i).val(data);
            });

            $.post('ajax/location.php',{name:name},function(data)
            {
                $('input#location_'+i).val(data);
            });
        }
    });
}

ajax/name.php and ajax/location.php are the files that retrieve data from DB. The output that I want is the data will appear in the name and location column according to the drop down menu data that I chose.

Upvotes: 0

Views: 191

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

This is a classic problem with use of a closure variable in a loop, the closure variable i is shared between all the change handlers, so at the end of the loop the value of i in all the change handlers will be 2 which will not match any elements

One solution in this case is to create a local closure for each loop iteration using IIFE

for (var i = 0; i < 2; i++) {
    (function (idx) {
        $('select#name_' + idx).on('change', function () {
            name = $(this).val();
            if ($.trim(name) != '') {
                $.post('ajax/name.php', {
                    name: name
                }, function (data) {
                    $('input#name-id_' + idx).val(data);
                });

                $.post('ajax/location.php', {
                    name: name
                }, function (data) {
                    $('input#location_' + idx).val(data);
                });

            }
        });

    })(i)
}

Another possible solution in this case may be is to use event data

for (var i = 0; i < 2; i++) {
    $('select#name_' + i).on('change', {
        index: i
    }, function (e) {
        name = $(this).val();
        if ($.trim(name) != '') {
            $.post('ajax/name.php', {
                name: name
            }, function (data) {
                $('input#name-id_' + e.data.index).val(data);
            });

            $.post('ajax/location.php', {
                name: name
            }, function (data) {
                $('input#location_' + e.data.index).val(data);
            });

        }
    });
}

Upvotes: 1

Related Questions