如何引用动态表单元素并保持以前的元素工作?

时间:2010-01-02 01:50:46

标签: php jquery mysql html-table

我已经做了很多搜索,所以如果我错过了,请原谅我,但这似乎很独特。

我有一个表格,我需要动态添加行(和字段),然后我需要jQuery来操作其中的一些字段,然后它们必须传递给PHP才能被转储到一个MySQL数据库。

除了jQuery操作字段之外,我已经完成了所有工作。基本上应该发生的是字段'unitprice'乘以字段'qty'并在'totalprice'字段中插入总数。问题是,因为我必须让这些字段具有不同的名称,因此它们都将传递给PHP,jQuery将仅在第一个字段上运行(当我删除数学代码中的+计数时),或者最近添加的(当+计数就在那里。

这是我添加行的jQuery代码(请注意,要使其在页面上看起来正确并且有一行可用,我必须有两个块,一个立即追加,一个点击链接:

     $(function(){
 $('#itemstablejquery').append(
 '<div class="jquery_items"><table id="jquery_items" width="100%" border="1" cellpadding="0" cellspacing="0"><tr><td width="10%">' 
 + '<input size="8" id="itemnum_' + count + '" name="itemnum[]' + '" type="text" /></td>'
 + '<td><input size="' + descwidth + '" id="description_' + count + '" name="description[]' + '" type="text" /></td>'
 + '<td width="5%"><input size="2" id="qty_' + count + '" name="qty[]' + '" type="text" /></td>'
 + '<td width="10%"><input size="' + unitpricewidth + '" id="unitprice_' + count + '" name="unitprice[]' + '" type="text" /></td>'
 + '<td width="11%"><input size="'+ totalpricewidth + '" id="totalprice_' + count + '" name="totalprice[]' + '" type="text" /></td>'
 + '</tr></table></div>'
 );

 });
 var count = 0;
 $(function(){
 $('p#add_field').click(function(){
 count += 1;
 $('#itemstablejquery').append(
 '<table id="jquery_items" width="100%" border="1" cellpadding="0" cellspacing="0"><tr><td width="10%">' 
 + '<input size="8" id="itemnum_' + count + '" name="itemnum[]' + '" type="text" /></td>'
 + '<td><input size="' + descwidth + '" id="description_' + count + '" name="description[]' + '" type="text" /></td>'
 + '<td width="5%"><input size="2" id="qty_' + count + '" name="qty[]' + '" type="text" /></td>'
 + '<td width="10%"><input size="' + unitpricewidth + '" id="unitprice_' + count + '" name="unitprice[]' + '" type="text" /></td>'
 + '<td width="11%"><input size="'+ totalpricewidth + '" id="totalprice_' + count + '" name="totalprice[]' + '" type="text" /></td>'
 + '</tr></table>'
 );

 });
 });

这是数学jQuery:

$("table#jquery_items").live("click", function(){
$('#totalprice_' + count).css('color', 'red')
$('input').blur(function() {
var price = $('#unitprice_' + count).val() 
var quantity = $('#qty_' + count).val() 
var total = price * quantity;
if (!isNaN(total)) {
$('#totalprice_' + count).attr('value', total)
} else {
alert('Ops Error! Please only numbers')
}
})
});

我的HTML:

<div id="itemstablejquery"><a name="items" id="items"></a>
    </div>
    <p id="add_field"><a href="#items"><span>&raquo; Add another item...</span></a></p>

由于

1 个答案:

答案 0 :(得分:0)

在.blur上,您没有提供被模糊字段的值(表示索引,计数或ID)。因此,js将只使用count变量的最后已知值。

我建议,如果你想使用.blur,请执行以下操作:

$('input').blur(function() {
    var indexArr = $(this).attr('id').split('_');
    var price = $('#unitprice'+indexArr[1]).val();
    ....
});