2016-09-30 49 views
-2

我是jQuery的新手。我試圖在每個動態添加的行上調用Blur函數,並將這兩個文本框的每行值都發送給PHP。
對於第一行,它的工作原理是動態添加行,但它不起作用。
我的代碼如下:
HTML和jQuery:jQuery:Blur函數不會調用每個動態添加的行

<!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; 


我沒有得到它。請建議我。提前感謝。

回答

0

使用on()在DOM上綁定動態添加的元素。

因爲當DOM準備就緒時,它沒有這些元素,當你動態添加這些元素時,DOM不理解這些元素。

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

我能看到你多個元素(文本框)具有相同的id #co_qty,它會導致問題。

您需要使用.co_qty才能應用於動態添加的元素。

+0

Thanks.But它只顯示每個動態行中調用的第一行的值。 – Soumya

+0

您需要將動態選擇器添加到動態添加的每個元素。 –