javascript - jQuery发票如何形成和删除按钮如何添加

标签 javascript jquery html css

我目前正在为自己开发一个动态发票系统。但我无法让它正常工作。

我想给这个表单添加一个删除按钮,但我做不到。

我有一个像这样的 HTML 发票表:

$('#addRow').click(function () {
    addItem();
});
$('#items_table').on('keyup', '.update', function () {
    var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
    if( key == 8 || key == 46 ) return false;
    calculateTotals();
});
$('#taxPercentage').change(function () {
    calculateTotals(); // user changed tax percentage, recalculate everything
});

function calculateTotals(){
    
    // get all of the various input typs from the rows 
    // each will be any array of elements
    var nameElements = $('.row-name');
    var quantityElements = $('.row-quantity');
    var taxElements = $('.row-tax');
    var priceElements = $('.row-price');
    var totalElements = $('.row-total');
    
    // get the bottom table elements
    var taxPercentageElement =$('#taxPercentage');
    var subTotalElement =$('#subTotal');
    var totalTaxElement =$('#totalTax');
    var grandTotalElement =$('#grandTotal');

    var subTotal=0;
    var taxTotal=0;
    var grandTotal=0;
    $(quantityElements).each(function(i,e){
        
        // get all the elements for the current row
        var nameElement = $('.row-name:eq(' + i + ')');
        var quantityElement = $('.row-quantity:eq(' + i + ')');
        var taxElement = $('.row-tax:eq(' + i + ')');
        var priceElement = $('.row-price:eq(' + i + ')');
        var totalElement = $('.row-total:eq(' + i + ')');

        // get the needed values from this row
        var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
            qty = qty == '' ? 0 : qty; // if blank default to 0
            quantityElement.val(qty); // set the value back, in case we had to remove soemthing
        var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
            price = price == '' ? 0 : price; // if blank default to 0
            priceElement.val(price); // set the value back, in case we had to remove soemthing
    
        // get/set row tax and total
        // also add to our totals for later
        var rowPrice = (price * 1000) * qty
            subTotal = subTotal + rowPrice;
        var tax = taxPercentageElement.val() * rowPrice;
            taxElement.val((tax / 1000).toFixed(2));
            taxTotal = taxTotal + tax;
        var total =   rowPrice + tax
            totalElement.val((total / 1000).toFixed(2));
            grandTotal = grandTotal + total;
    });
    
    // set the bottom table values
    subTotalElement.val((subTotal / 1000).toFixed(2));   
    totalTaxElement.val((taxTotal / 1000).toFixed(2));  
    grandTotalElement.val((grandTotal / 1000).toFixed(2));   
}
function addItem() {
    var itemRow =
        '<tr>' +
        '<td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
        '<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
        '<td><input type="text" class="form-control update row-tax" placeholder="Tax" /></td>' +
        '<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
        '<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
        '</tr>';
    $("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
    font-size:18px;
    
}
.myTable {
    background-color:#ffaa56;
}
.myTable {
    border-collapse: collapse;
    border-spacing: 0;
    width:100%;
    height:100%;
    margin:0px;
    padding:0px;
}
.myTable tr:last-child td:last-child {
    -moz-border-radius-bottomright:0px;
    -webkit-border-bottom-right-radius:0px;
    border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
    -moz-border-radius-topleft:0px;
    -webkit-border-top-left-radius:0px;
    border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
    -moz-border-radius-topright:0px;
    -webkit-border-top-right-radius:0px;
    border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
    -moz-border-radius-bottomleft:0px;
    -webkit-border-bottom-left-radius:0px;
    border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
    background-color:#ffffff;
}
#items_table tr:nth-child(even) {
    background-color:#ffd0a3;
}
.myTable td {
    vertical-align:middle;
    border:1px solid #000000;
    border-width:0px 1px 1px 0px;
    text-align:left;
    padding:7px;
    font-size:10px;
    font-family:Arial;
    font-weight:normal;
    color:#000000;
}
.myTable tr:last-child td {
    border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
    border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
    border-width:0px 0px 0px 0px;
}

html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
    <thead>
        <tr>
            <th>Item Name</th>
            <th>Quantity</th>
            <th>Tax</th>
            <th>Price</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody id="items_table"></tbody>
    <tfoot>
        <tr>
            <th>Item Name</th>
            <th>Quantity</th>
            <th>Tax</th>
            <th>Price</th>
            <th>Total</th>
        </tr>
    </tfoot>
</table>
<br>
    <br>
<table class="myTable" style="width:70%">
    <thead>
        <tr>
            <th>Tax Percentage</th>
            <th>Sub Total</th>
            <th>Total Tax</th>
            <th>Grand Total</th>
        </tr>
    </thead>
    <tbody id="items_table">
        
        
        <tr>
            <td>
                <select name="" id="taxPercentage" class="form-control">
                    <option value=".10">10%</option>
                    <option value=".15">15%</option>
                </select>
            <td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
            <td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
            <td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
        </tr>
        
    </tbody>
    <tfoot>
    </tfoot>
</table>

我目前对如何正确执行此操作一无所知。所以,我只需要填充 1 个元素行,在添加的总表中添加税金,一旦我更改该行中的税金,它也会在下方更改,并且价格也必须更改。

有人可以让我走上正轨吗?

最佳答案

I want to add delete button to this form but I can not do it

这里的关键是要了解事件处理程序通常只能在设置时页面上出现的元素上设置。您的代码失败是因为您动态添加了行 - 当您尝试分配事件处理程序时它们不存在。然而,jQuery 为我们提供了特殊形式的 on() function,它涵盖了我们在这种情况下需要的内容:

$('already present parent element selector').on("click", "existing/added later element selector", function () {
    //code
});

因此,为了解决您的问题,您的代码应如下所示:

$('body').on("click", "#delRow", function () {
    delItem($(this));
});
function delItem(elem) {
   elem.parents("tr").remove();
   calculateTotals();
}

请注意,您必须在 #delRow 函数和标记中相应的 addItem() 单元格中将 <th> 按钮添加到模板。

关于整个事情,我也会禁用税收单元格,因为如果用户可以编辑它就没有意义,因为税收总额是由下面的百分比值定义的(10% 或 15%)。税收通常由政府征收。并且提前知道。我的意思是你不能只支付 5.745632% 而不是法律规定的 15%。

我还发现了一个小问题:当我删除 price 单元格中的符号时,更新不会执行,相关单元格的值也不会相应更改。您可能想阅读 MDN 上的 input 事件。

一般来说,如果我正确理解了您的想法,它就可以正常工作:

$('#addRow').on("click", function () {
    addItem();
});
$('body').on("click", "#delRow", function () {
    delItem($(this));
});
$('#items_table').on('input', '.update', function () {
    var key = event.keyCode || event.charCode; // if the user hit del or backspace, dont do anything
    if( key == 8 || key == 46 ) return false;
    calculateTotals();
});
$('#taxPercentage').change(function () {
    calculateTotals(); // user changed tax percentage, recalculate everything
});

function calculateTotals(){
    
    // get all of the various input typs from the rows 
    // each will be any array of elements
    var nameElements = $('.row-name');
    var quantityElements = $('.row-quantity');
    var taxElements = $('.row-tax');
    var priceElements = $('.row-price');
    var totalElements = $('.row-total');
    
    // get the bottom table elements
    var taxPercentageElement =$('#taxPercentage');
    var subTotalElement =$('#subTotal');
    var totalTaxElement =$('#totalTax');
    var grandTotalElement =$('#grandTotal');

    var subTotal=0;
    var taxTotal=0;
    var grandTotal=0;
    $(quantityElements).each(function(i,e){
        
        // get all the elements for the current row
        var nameElement = $('.row-name:eq(' + i + ')');
        var quantityElement = $('.row-quantity:eq(' + i + ')');
        var taxElement = $('.row-tax:eq(' + i + ')');
        var priceElement = $('.row-price:eq(' + i + ')');
        var totalElement = $('.row-total:eq(' + i + ')');

        // get the needed values from this row
        var qty = quantityElement.val().trim().replace(/[^0-9$.,]/g, ''); // filter out non digits like letters
            qty = qty == '' ? 0 : qty; // if blank default to 0
            quantityElement.val(qty); // set the value back, in case we had to remove soemthing
        var price = priceElement.val().trim().replace(/[^0-9$.,]/g, '');
            price = price == '' ? 0 : price; // if blank default to 0
            priceElement.val(price); // set the value back, in case we had to remove soemthing
    
        // get/set row tax and total
        // also add to our totals for later
        var rowPrice = (price * 1000) * qty
            subTotal = subTotal + rowPrice;
        var tax = taxPercentageElement.val() * rowPrice;
            taxElement.val((tax / 1000).toFixed(2));
            taxTotal = taxTotal + tax;
        var total =   rowPrice + tax
            totalElement.val((total / 1000).toFixed(2));
            grandTotal = grandTotal + total;
    });
    
    // set the bottom table values
    subTotalElement.val((subTotal / 1000).toFixed(2));   
    totalTaxElement.val((taxTotal / 1000).toFixed(2));  
    grandTotalElement.val((grandTotal / 1000).toFixed(2));   
}
function delItem(elem) {
   elem.parents("tr").remove();
   calculateTotals();
}
function addItem() {
    var itemRow =
        '<tr>' +
        '<td><button id="delRow">Delete</button></td><td><input type="text" class="form-control row-name" placeholder="Item name" /></td>' +
        '<td><input type="text" class="form-control update row-quantity" placeholder="Quantity" /></td>' +
        '<td><input type="text" disabled class="form-control update row-tax" placeholder="Tax" /></td>' +
        '<td><input type="text" class="form-control update row-price" placeholder="Price" /></td>' +
        '<td><input type="text" class="form-control row-total" disabled placeholder="0,00" /></td>' +
        '</tr>';
    $("#items_table").append(itemRow);
}
addItem(); //call function on load to add the first item
button{
    font-size:18px;
    
}
.myTable {
    background-color:#ffaa56;
}
.myTable {
    border-collapse: collapse;
    border-spacing: 0;
    width:100%;
    height:100%;
    margin:0px;
    padding:0px;
}
.myTable tr:last-child td:last-child {
    -moz-border-radius-bottomright:0px;
    -webkit-border-bottom-right-radius:0px;
    border-bottom-right-radius:0px;
}
.myTable tr:first-child td:first-child {
    -moz-border-radius-topleft:0px;
    -webkit-border-top-left-radius:0px;
    border-top-left-radius:0px;
}
.myTable tr:first-child td:last-child {
    -moz-border-radius-topright:0px;
    -webkit-border-top-right-radius:0px;
    border-top-right-radius:0px;
}
.myTable tr:last-child td:first-child {
    -moz-border-radius-bottomleft:0px;
    -webkit-border-bottom-left-radius:0px;
    border-bottom-left-radius:0px;
}
.myTable tr:hover td {
}
#items_table tr:nth-child(odd) {
    background-color:#ffffff;
}
#items_table tr:nth-child(even) {
    background-color:#ffd0a3;
}
.myTable td {
    vertical-align:middle;
    border:1px solid #000000;
    border-width:0px 1px 1px 0px;
    text-align:left;
    padding:7px;
    font-size:10px;
    font-family:Arial;
    font-weight:normal;
    color:#000000;
}
.myTable tr:last-child td {
    border-width:0px 1px 0px 0px;
}
.myTable tr td:last-child {
    border-width:0px 0px 1px 0px;
}
.myTable tr:last-child td:last-child {
    border-width:0px 0px 0px 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addRow">Add a row</button><br><br>
<table class="myTable">
    <thead>
        <tr><th>Delete</th>
            <th>Item Name</th>
            <th>Quantity</th>
            <th>Tax</th>
            <th>Price per unit</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody id="items_table"></tbody>
    <tfoot>
        <tr><th>Delete</th>
            <th>Item Name</th>
            <th>Quantity</th>
            <th>Tax</th>
            <th>Price per unit</th>
            <th>Total</th>
        </tr>
    </tfoot>
</table>
<br>
    <br>
<table class="myTable" style="width:70%">
    <thead>
        <tr>
            <th>Tax Percentage</th>
            <th>Sub Total</th>
            <th>Total Tax</th>
            <th>Grand Total</th>
        </tr>
    </thead>
    <tbody id="items_table">
        
        
        <tr>
            <td>
                <select name="" id="taxPercentage" class="form-control">
                    <option value=".10">10%</option>
                    <option value=".15">15%</option>
                </select>
            <td><input type="text" class="form-control" id="subTotal" disabled placeholder="0,00" /></td>
            <td><input type="text" class="form-control" id="totalTax" disabled placeholder="0,00" /></td>
            <td><input type="text" class="form-control" id="grandTotal" disabled placeholder="0,00" /></td>
        </tr>
        
    </tbody>
    <tfoot>
    </tfoot>
</table>

至于您的附加问题 - 您可以选择一种语言环境,以按照您所在国家/地区的格式将数字视为货币。可以通过 toLocaleString() 来完成:

var num1 = 145636,
    num2 = 145636;

console.log(num1.toLocaleString('en-US', {style: 'currency', currency: 'USD'})); // US format - 145,636
console.log(num2.toLocaleString('en-IN', {style: 'currency', currency: 'INR'})); // Indian format - 1,45,636

关于javascript - jQuery发票如何形成和删除按钮如何添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47005915/

相关文章:

javascript - 在保持基本功能的同时扩展 Backbone 功能

javascript - Ajax 发出太多请求

javascript - 添加缓存文件 .appcache 停止 jquery ajax 调用

javascript - HTML 元素无法在 Samsung Tab Active2 Tablet 上的 chrome 中正确打开

javascript - 在 HTML 音频播放器中切换播放/暂停按钮

css - 顶部分区的溢出影响其下方分区的属性

JavaScript 选中所有复选框并取消选中所有复选框

javascript - jQuery 选择器返回什么样的对象?

javascript - 如何从您的网站使用语音识别搜索谷歌?

javascript - 居中主 div 中的三个 div