【问题标题】:how to select input in datatable using jquery如何使用jquery在数据表中选择输入
【发布时间】:2018-03-02 23:47:12
【问题描述】:

我正在使用 create row 函数在数据表中生成行,我想选择 add_quantity 字段和 price_input 字段并进行一些计算并将它们显示在 DataTable 中每一行的 total_price 字段中

我正在做这样的事情,但我能得到唯一的第一行字段其余行仍然未计算

这就是我在cart_table 中创建行的方式

var t = $('#cart_table').DataTable();

            // $('#add-to-cart_table').on( 'click','.btn-cart', function () {
                t.row.add( [
                    $(this).data('id'),
                    $(this).data('name'),
                    (`<input type="text" id="add_qty" class="prdt-qty" style="width:30px">`),
                    (`  
                        <div class="form-check form-check-inline">
                            <label class="form-check-label">
                                <input class="form-check-input" type="checkbox" checked id="price_checkbox"> 
                            </label>
                            <input type="text" id="price_input" value= "`+$(this).data('by_p') +`" class="disable-form">
                        </div>
                    `),
                    (`<input type="text" disabled id="total_price" class="prdt-qty" style="width:30px">`),
                    ('<a href="#" class="btn btn-xs btn-delete"><i class="fa fa-trash-o"></i></a>')
                ] ).draw( false );

这就是我选择行字段来计算的方式

$('#cart_table').on('click', 'tr', function () {
    var table = $('#cart_table').DataTable();

    var data = table.row(this);
    var qty = $('#add_qty').val();
    var price = $('#price_input').val();
    $('#add_qty').on('keyup',function(){
        qty = $(this).val();
        if(qty >=1 ){
            $('#total_price').val(qty*price);
        }
        else{
            $('#total_price').val(qty);
        }
        console.log(qty);
        console.log(price);
    })
        console.log(data);

} );

【问题讨论】:

    标签: jquery select datatable field using


    【解决方案1】:

    因为您在多个元素上使用相同的 id。 id 是唯一的,不要在多个元素上使用相同的 id。您可以改用类。

    $('#price_input') => 只返回 id = price_input 的第一个元素 $('.price_input') => 返回所有 class=price_input 的元素

    但我们可以使用 $('input[id="price_input"]') => return all id=price_input 属性的元素来破解它

    $('#cart_table').on('keyup', 'input[id="add_qty"]', function () {
        var tr= $(this).find('tr');
        var qty = $(this).val();
        var price = tr.find('#price_input').val();
    
            if(qty >=1 ){
                tr.find('input[id="total_price"]').val(qty*price);
            }
            else{
                tr.find('input[id="total_price"]').val(qty);
            }
            console.log(qty);
            console.log(price);
    
    });
    

    【讨论】:

    • 不工作,我想获取所选行输入字段的值,然后进行一些计算并返回
    猜你喜欢
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    相关资源
    最近更新 更多