2016-12-06 72 views
0

基于数量的数量价格,我想创建一个购物车,其中一个客户选择自动添加到cart.and基于量价的数量可以更新自动完成搜索的项目。我已成功添加到购物车,但无法动态更新价格。 任何人都可以点我什么是与现有的代码中的错误:如何更新使用jQuery

$('#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); 
     }); 
    }     
}); 

下面是表的部分代码:

<table class="table table-striped table-bordered" id="example"> 
    <thead> 
     <tr>       
      <td>ID</td> 
      <td>Name</td> 
      <td>Price</td> 
      <td>Quantity</td> 
      <td>Total</td>      
     </tr> 
    </thead> 
    <tbody> 
    </tbody> 
</table> 

错误我越来越:

enter image description here

+2

每一行与“量”的相同ID的元素 – abc123

+2

'id's都必须是唯一的,但你会有''数量''ID =“数量”'''''ID =“总数”'。那么你认为怎样的JavaScript就会知道哪些'$(“#数量”)'或'$(“#总”)'你选择? – Sean

回答

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);  
     }); 
+0

你的代码的问题是总更新基础上的数量,但不是在确切的行名称。是指总的更新基于最后一个项目的价格,而我改变量 – Hola

+0

我更新的代码。请检查。你是对的。因为它获得相同的价格。我稍微改变了一下代码。 – SilentCoder

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 
}); 
+0

我总的第一次,但是当我更新数量..它无法更新的总价格与您的代码。 – Hola

+0

@Hola我添加了一个答案。希望这会帮助你。 – SilentCoder