在下面的小提琴中,我编写了将文本框(数量,价格)和选择框(税收%)值相乘的代码,并用计算(javascript函数)的结果填充总文本框值。
请参阅小提琴http://jsfiddle.net/fvJgE/13/获取代码。任何人都可以发现我错过了什么或我做错了什么?
jQuery代码
var count = 1;
$(document).ready(function () {
$("#addButton").click(function () {
if(count>7){
alert("Only 7 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + count);
newTextBoxDiv.after().html(
'<label>Desc #'+ count + ' : </label>' +
'<input type="text" size="4" name="desc[]" id="desc' + count + '" value="" > \n\
<label>Tax #'+ count + ' : </label>' +
'<select id="tax_type' + count + '" ><option value="tax1">VAT</option><option value="tax2">ST</option></select> \n\
<label>Tax% #'+ count + ' : </label>' +
'<select id="tax_per' + count + '" ><option value="Vat">5.5</option><option value="ST">14.5</option></select> \n\
<label>Qty #'+ count + ' : </label>' +
'<input type="text" size="1" name="qty[]" id="qty' + count + '" value="" > \n\
<label>price #'+ count + ' : </label>' +
'<input type="text" size="2" name="price[]" id="price' + count + '" value="" > \n\
<label>Total #'+ count + ' : </label>' +
'<input type="text" size="3" name="total[]" id="total' + count + '" value="" >'
);
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#qty' + count).on("blur", function() {
calculate($(this));
});
$('#price' + count).on("blur", function() {
calculate($(this));
});
$('#tax_per' + count).on("change", function() {
calculate($(this));
});
count++;
});//closing the addButton function
//To caluculate Total amount based on price and tax percentage
function calculate(el) {
var count = el.attr("id").indexOf("qty") != -1 ? el.attr("id").substring(3) : el.attr("id").substring(5);
var qty = isNaN(parseFloat($('#qty' + count).val())) ? 0 : parseFloat($('#qty' + count).val());
var price = isNaN(parseFloat($('#price' + count).val())) ? 0 : parseFloat($('#price' + count).val());
var tax_per = isNaN(parseFloat($('#tax_per' + count).val())) ? 0 : parseFloat($('#tax_per' + count).val());
var value = qty*price;
//alert(value);
var tax_amt = (value*tax_per)/100;
//alert(tax_amt);
var total_value = value + tax_amt;
$("#total" + count).val(total_value);
}
//To remove the added textboxes
$("#removeButton").click(function () {
if(count==0){
alert("No more textbox to remove");
return false;
}
count--;
$("#TextBoxDiv" + count).remove();
});
});
HTML 代码
<table>
<tr>
<td>
<input type="button" id="addButton" value="Add" class="add" >
<input type="button" id="removeButton" value="Delete" class="remove" >
</td>
</tr>
</table>
<table>
<tr>
<td>
<div id='TextBoxesGroup'>
</div>
</td>
</tr>
</table>
该值显示在 Total 文本框中,但在计算中不考虑 selectbox(Tax%) 值。在此先感谢您的帮助。