Arti Arti - 3 months ago 14
Javascript Question

Dynamically created select list makes mutilple calls to javascript function

I have created dynamically multiple select list. On click of channel name it should get its type. The problem is once click on select list its repetitively calls java script function causing ajax to load multiple times.

HTML CODE:

<td>
<SELECT name="channel_name[]" onclick ="get_type(this)"; required class='channelname'>
<option value="">Select...</option>
<?php foreach($channel_list as $row) {
$channelid = $row['channelid'];
$channelname = $row['channelname'];

if($U_channelid==$channelid)
{
$s = "selected = selected";
}
else
{
$s = "";
}
echo "<option value='$channelid' $s>".$channelname."</option>";
?>
<!-- <OPTION value='<?php echo $channelid ?>' $s ><?php echo $channelname?></OPTION> -->

<?php } ?>
</SELECT>
</td>


Javascipt code:

function get_type()
{
$(".channelname").live("change", function() {

var channel_id = $(this).find("option:selected").attr("value");
var _this = $(this); //Save current object
alert(channel_id);
$.ajax({
type: "POST",
url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
data: 'channelid='+channel_id,
async: false
}).done(function( data1 ) {

if(data1){
_this.closest("tr").find('input[name="type[]"]').val(data1);

}else{
alert("Channel type is not defined");
_this.closest("tr").find('input[name="type[]"]').val("");

}


});
});
}

Answer

remove onclick ="get_type(this)" from select tag // because you already using $(".channelname").live("change", function() { in javascript

put this

<SELECT name="channel_name[]" required class='channelname'>

and javascript

$(".channelname").change(function() {

                var channel_id = $('.channelname').find("option:selected").attr("value");
                alert(channel_id);
                $.ajax({
                        type: "POST",
                        url: '<?php echo base_url(); ?>index.php/partner/get_channel_type',
                        data: 'channelid='+channel_id,
                        async:   false
                         }).done(function( data1 ) {

                        if(data1){
                                _this.closest("tr").find('input[name="type[]"]').val(data1);

                        }else{
                                alert("Channel type is not defined");
                                 _this.closest("tr").find('input[name="type[]"]').val("");

                        }


                });
    });