如何使用jquery根据数量更新价格

时间:2016-12-06 04:42:15

标签: javascript php jquery

我想创建一个购物车,其中客户从自动完成搜索中选择一个项目,自动添加到购物车。并根据可以更新的数量价格数量。我已成功添加到购物车但我无法动态更新价格。 任何人都可以指出我现有代码的错误:

StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
FileReader reader = new FileReader("entry.ldif");
LdifReader ldifReader = new LdifReader(reader);
SearchResult result = ldifReader.read();
jsonWriter.write(result);
System.out.println(writer.toString());

这是表格部分代码:

$('#searchName').autocomplete({
    source: '{!! asset('nameAutocomplete') !!}',
    select:function(suggestion,ui){
        event.preventDefault();
        var $tbody = $('#example tbody');
        $tbody.append('<tr><td class="id">' + ui.item.id +
            '</td><td class="name">' + ui.item.value +
            '</td><td class="price" id="price">' + ui.item.price +
            '</td><td><input type="text" id="quantity" value="1"/></td><td><input type="text" id="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');

        $('#quantity').on('keyup',function(){
            var tot = ui.item.price * this.value;
            $('#total').val(tot);
        });  
    }                   
});

错误我得到了:

enter image description here

2 个答案:

答案 0 :(得分:2)

使用以下代码检查,我在@Mayank代码中添加了一点点,

     var $tbody = $('#example tbody');
        $tbody.append('<tr><td class="id">' + ui.item.id +
        '</td><td class="name">' + ui.item.value +
        '</td><td class="price">' + ui.item.price +
        '</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');


        $('.quantity').on('keyup',function(){
           //Corrected part
            var tot = $(this).parent().prev().html() * this.value;
           //var tot = ui.item.price * this.value;
           //Assume that you are getting correct value to tot variable
           $(this).parent().next().find('.total').val(tot);      
        });

答案 1 :(得分:0)

在代码中进行以下更改,如:

var $tbody = $('#example tbody');
$tbody.append('<tr><td class="id">' + ui.item.id +
    '</td><td class="name">' + ui.item.value +
    '</td><td class="price">' + ui.item.price +
    '</td><td><input type="text" class="quantity" value="1"/></td><td><input type="text" class="total" readonly value="'+ui.item.price+'" class="readonly"/></td></tr>');

    // Use class in place of id, as you cannot work with id for multiple occurance of same html

$('.quantity').on('keyup',function(){
    var tot = ui.item.price * this.value;
    $(this).find('.total').val(tot);    // Use DOM traverse to get the next <input type="text" /> and put new total value to it
});