Reputation: 2233
I want to create a shopping cart where a client select an item from the autocomplete search automatically added to cart.and based on the number of quantity price can be updated. I have added to the cart successfully but I couldn't update the price dynamically. Can anyone point me out what's the error with the existing code:
$('#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);
});
}
});
Here is the table part code :
<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>
Error I'm getting :
Upvotes: 0
Views: 2336
Reputation: 2000
Check with following code,I added little bit to @Mayank code,
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);
});
Upvotes: 2
Reputation: 26258
Make following changes in code like:
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
});
Upvotes: 0