0

I am using the jQuery DataTables plugin, it has one event, that on click of button we can add new row in table.
The jQuery code is as below:

$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
    t.row.add( [
         counter,
        '<select id="k'+counter+'" name="itemname'+counter+'" ><option>-------</option></select>' ,
        '<input id="itemrate" name="itemqty'+counter+'"  placeholder="Quantity"  type="text">',
        '<input id="itemrate" name="itemrate'+counter+'"  placeholder="Rate"  type="text">',
        '<input id="totalamt" name="totalamt'+counter+'"  placeholder="Total Amount"  type="text">'
                ] ).draw();
                counter++;
            }); 
    });

I want to fill data fetched from a MySQL database using jQuery .ajax(), and my code is as follows:

jQuery(document).ready(function(){
    jQuery('#k'+counter).click(function(){
        jQuery.ajax({
            url: 'getData.php',
            type:'POST',
            data:'form_data='+val,
            success:function(results){
                jQuery('#k'+counter).html(results);
            }
        });
    }); 
    });

The code for getdata.php is as follows:

<?php

mysql_connect('localhost','root','');
mysql_select_db('eroyalsum');

$sql = "SELECT ITEMCODE,ITEMNAME FROM itemmaster1";
$result = mysql_query($sql);

while($row = mysql_fetch_row($result))
{
    echo '<option value="'.$row[0].'" >'.$row[1].'</option>';
}

?>

Finally, my problem is when I write it as separate function, it just works only once. When I add other row it does not work, and when i write jQuery's .ajax() in one function it does not work...

smottt
  • 3,272
  • 11
  • 37
  • 44
hiren parmar
  • 11
  • 1
  • 2

2 Answers2

0

try changing you selector from:

jQuery('#k'+counter).click(function(){
…

to

jQuery(document).on("change", "select[id^='k']", function(){
...
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

The issue is the event binding.

When you bind the event to the #k elements, the new item doesn't automatically get the event bound to it.

You can use stuff like :

$('body').on('click','.new_elements',function(){ //dostuff});

you can read more about it here

Event binding on dynamically created elements?

Community
  • 1
  • 1
Patrick
  • 3,289
  • 2
  • 18
  • 31