Reputation: 3
I need your help please! I want to multiply the quantity with the single price and put it in id called total using Ajax( I don't know Ajax well)
$(function () {
"use strict";
$('.qty').on('keyup', function () {
var singl_price = $(".single_price").val(),
qty = $(".qty").val(),
total_price = qty * singl_price;
$("#total").text(total_price);
$.ajax({
url: 'cart.php',
type: 'POST',
data: '',
success: function (data) {
if (data === "ok") {
}
},
error: function (e) {
}
});
});
});
<form action="cart.php" method="post" >
<input type="text" name="qty" class="qty" value="<?php echo $_POST['qty']; ?>" />
</form>
<div class="single_price"> 20 </div>
<div id="total"> </div>
Upvotes: 0
Views: 1438
Reputation: 32354
try:
$('.qty').on('keyup', function () {
$.ajax({
url: 'cart.php',
type: 'POST',
data: {total_price:total_price},
success: function (data) {
var total = 0;
$('.qty').each(function(i,v){
var singl_price = $(v).next(".single_price").text();
var qty = $(v).val().length > 0 ?$(v).val():0;
total += parseInt(qty) * parseInt(singl_price);
});
$('#total').text(total);
if (data === "ok") {
}
},
error: function (e) {
}
});
});
html:
<form action="cart.php" method="post" >
<input type="text" name="qty" class="qty" value="<?php echo $_POST['qty']; ?>" />
<div class="single_price"> 20 </div>
</form>
<div id="total">0</div>
https://jsfiddle.net/o7hb7s6g/2/
Note:use parseFloat instead of parseInt if you have price with like 3.99
Upvotes: 1
Reputation: 1517
qty = $(".qty").val(),
Thats looking for an element with a class of qty, but you only have an element with a name of qty. You can add the class="qty"
or try to look up using $("[name=qty]")
which is a much slower selector. I would suggest reviewing jquery selectors
In addition, I'm not really sure what you are trying to do with your ajax code. If you are just trying to submit the form, $('form').submit()
would work.
If you are trying to post, then:
$.ajax({
url: 'cart.php',
type: 'POST',
data: { qty: qty }, // Data you want to submit
success: function (data) {
if (data === "ok") {
}
},
error: function (e) {
}
});
Upvotes: 0