I have the following structure:
<table>
<tr>
<td>first</td>
<td class="price">__</td>
<td><input type="text" class="quantity"></td>
<td class="amount></td>
</tr>
</table>
Inside the <td class="price">
goes a value that is retrieved through AJAX function.
So I have this on my javascript file:
jQuery(function($) {
$(document).ready(function() {
// alert('document ready');
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = $this.val();
price = $this.prev("td.price").text();
alert(price);
amount = quantity * price;
$this.next("td.amount").html(amount);
});
});
});
but price returns nil (even price being loaded correctly thro my ajax function)
EDIT: This is the final code following all suggestions below. Thank you all!
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = parseInt($this.val()); // in this case, people can't buy a 1 item and a half for example.
price = $this.parents("tr").find("td.price").text();
price = parseFloat(price); // price can have "cents"
amount = quantity * price;
amount = Number(amount).toFixed(2); // I shoul开发者_JS百科d be able to see at least 2 first decimal digits from the amount.
$this.parent().next("td.amount").html(amount);
});
To get your previous / next elements you could use the following:
parseInt($this.parent().prev("td.price").text()); //or parseFloat
and
parseInt($this.parent().next("td.amount").text()); //or parseFloat
Full Code:
jQuery(function($) {
$(document).ready(function() {
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = parseInt($this.val());
alert("Quantity : " + quantity);
price = parseInt($this.parent().prev("td.price").text());
alert("Price : " + price);
amount = quantity * price;
$this.parent().next("td.amount").html(amount);
alert("Amount : " + amount);
});
});
Working Demo
It should be:
price = $this.parents("tr").find("td.price").text();
Live test case.
This may be a datatype issue when doing your mulitplication.
Check out:
parseFloat
parseInt
Try:
jQuery(function($) {
$(document).ready(function() {
// alert('document ready');
$("input.quantity").live("blur", function() {
var $this = $(this);
quantity = $this.val();
price = $this.parent().siblings("td.price").text();
price=parseFloat(price);
alert(price);
amount = quantity * price;
$this.parent().siblings("td.amount").html(amount);
});
});
});
精彩评论