我正在尝试使用一个简单的javascript函数,该函数旨在与单个数字的SELECT下拉列表一起使用,但现在我需要在访问者输入带小数点的值时使用它。即使我输入30或任何数字,我使用当前的javascript获得NaN。关于如何获得我的总数的任何建议?
JAVASCRIPT:
$(function () {
$('.DoPricing').change(function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseInt($(this).val());
});
$('#TotalPrice').html('$' + total);
});
});
HTML:
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying today?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
答案 0 :(得分:5)
试试这个:
$(function () {
$('.DoPricing').on("keyup",function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseFloat($(this).val()) || 0;
});
$('#TotalPrice').html('$' + total);
});
});
现在接受小数,这里是demo
答案 1 :(得分:2)
Your basic example works for me.我猜there are other elements on the page with class, but that don't necessarily have values,你希望它们默认为零。当输入没有值时,.val()
会返回空字符串,parseInt('', 10)
会返回NaN
,而不会返回0
,因此您无法获得所需内容。
这很容易解决:
total += parseInt($(this).val()) || 0;
答案 2 :(得分:0)
我假设您也想要小数,但是您使用的是parseInt而不是parseFloat,如果您使用小数(因为它是金钱),那么您应该使用toFixed。在下面的代码中我假设用户将使用。作为小数符号,应该只有一个。在值(没有千位分隔符)。
在你的每一个中你将一个非常好用的转换为jQuery对象只是为了获得值。我已将$(this).val()更改为this.value,因此不需要转换。
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="jquery-1.9.0.js"></script>
</head>
<body>
<form action="myactionpage.php" method="POST">
<table>
<tr>
<td>How much will you be paying this morning?</td>
<td>$<input type="text" name="howmuch" id="howmuch" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td>How much will you be paying this evening?</td>
<td>$<input type="text" name="howmuch" id="howmuch1" placeholder="0.00" class="DoPricing"></td>
</tr>
<tr>
<td><div class="totalbox">Total Amount Due Today: <strong><span id="TotalPrice">$0.00</span></strong></div>
</td>
</tr>
<tr><td><input type="submit" id="submit" name="submit" value="Submit Payment" class="submitbut" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
(function () {
function getValue(el) {
if (el.value === "") { return 0; }
var nr = parseFloat(el.value);
// only 0 to 9 or . and only one . used as decimal symbol
if (/[^0-9.]/.test(el.value) || /.*?\..*?\./.test(el.value)) {
return false;
}
return nr;
}
$('.DoPricing').on("keyup", null, null, function (e) {
var $this = $(this),
val = getValue(this),
total = 0;
if(val!==false){
$this.data("pref",val);
}else{
$this.val($this.data("pref")||"");
}
$('.DoPricing').each(function () {
total += parseFloat(this.value,10)||0;
});
$('#TotalPrice').html('$' + total.toFixed(2));
});
})();
</script>
</body>
</html>