-2

I am newbie to jQuery.I am trying to call the Blur function on each dynamically Added row and send the values of each row of both text box to PHP.
For first row, it works but dynamically added rows, its not working.
My Code is as follows:
HTML and Jquery:

 <!doctype HTML>
    <html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    </head>
    <script type="text/javascript">
    var rowCount = 1;
    function addMoreRows(frm) {
    rowCount ++;
    var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" id="co_name" size="17%"  maxlength="120" /></td><td><input name="" type="text"  id="co_qty" maxlength="120" style="margin: 4px 5px 0 5px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
    jQuery('#addedRows').append(recRow);
    }

    function removeRow(removeNum) {
    jQuery('#rowCount'+removeNum).remove();
    }
    </script>
    <body>
    <table rules="all" style="background:#fff;">
    <tr>
    <td style="font-size:14px;" >Name</td>
    <td style="font-size:14px;" >Email</td>

    <td><span style="font:normal 12px agency, arial; color:blue; text-decoration:underline; cursor:pointer;" onclick="addMoreRows(this.form);">
    Add More
    </span>
    </td>
    </tr>
    <tr id="rowId">
    <td><input name="" type="text"  id="co_name" value="" size="17%"/></td>
    <td><input name="" type="text" id="co_qty" value="" /></td>

    </table>
    <div id="addedRows"></div>
    </td>
    </tr>
    <script>
    $(document).ready(function(){
        $('#co_qty').on('blur',function () {
    var username = $('#co_name').val(); 
     var password = $('#co_qty').val(); 
    $.ajax({
             type: "POST",
             url: "blur.php",
             data: {'title':username ,'title1':password},
             success: function(msg) {
      alert(msg)             }

    }); 
     });
    });

    </script>
    </body>
    </html><br>

blur.php

$var=$_POST['title'];
$var1=$_POST['title1'];
echo $var."Success!".$var1;


I am not getting it. Please do suggest me.Thanks in advance.

Soumya
  • 67
  • 1
  • 6

1 Answers1

0

Use on() to bind dynamically added elements on DOM.

Because when DOM is ready, it doesn't have those elements and when you add those dynamically, DOM doesn't understand those.

$('body').on('blur','.co_qty', function () {
   //Your code
});

And I can see that you've multiple elements (text-box) with same id #co_qty, it cause problems.

You need to use .co_qty to apply on dynamically added elements.

Mohit Tanwani
  • 6,503
  • 1
  • 11
  • 31