$(document).ready(
function (){
// bind the recalc function to the quantity fields
$("input[name^=qty_item_]").bind("keyup", recalc);
// run the calculation function now
recalc();
// automatically update the "#totalSum" field every time
// the values are changes via the keyup event
$("input[name^=sum]").sum("keyup", "#totalSum");
// automatically update the "#totalAvg" field every time
// the values are changes via the keyup event
$("input[name^=avg]").avg({
bind:"keyup"
, selector: "#totalAvg"
// if an invalid character is found, change the background color
, onParseError: function(){
this.css("backgroundColor", "#cc0000")
}
// if the error has been cleared, reset the bgcolor
, onParseClear: function (){
this.css("backgroundColor", "");
}
});
}
);
function recalc(){
$("[id^=total_item]").calc(
// the equation to use for the calculation
"qty * price",
// define the variables used in the equation, these can be a jQuery object
{
qty: $("input[name^=qty_item_]"),
price: $("[id^=price_item_]")
},
// define the formatting callback, the results of the calculation are passed to this function
function (s){
// return the number as a dollar amount
return "$" + s.toFixed(2);
},
// define the finish callback, this runs after the calculation has been complete
function ($this){
// sum the total of the $("[id^=total_item]") selector
var sum = $this.sum();
$("#grandTotal").text(
// round the results to 2 digits
"$" + sum.toFixed(2)
);
}
);
}
</script>
<table width="500">
<tr>
<td align="center"><input type="text" name="qty_item_1" id="qty_item_1" value="1" size="2" /></td>
<td align="center" id="price_item_1">$9.99</td>
<td align="center" id="total_item_1">$9.99</td>
</tr>
</table>
我正在使用jquery计算产品和数量,有没有办法使数量必须小于20,在jquery和通过验证error.ie:如果用户输入数量&gt; 20然后它需要显示jquery错误,否则需要允许用户输入。
答案 0 :(得分:0)
试试这个小提琴
答案 1 :(得分:0)
您可以使用jQuery验证插件(http://docs.jquery.com/Plugins/validation),这对于此类场景非常有用。
将表格包裹在带有ID的表格中,例如:
<form id="items">
...your table markup
</form>
初始化如下:
$(function () {
$('#items').validate(
rules: {
'qty_item_1': { required: true, max: 20 }
},
messages: {
'qty_item_1': 'Please enter a value less than 20'
}
);
});
然后,在你的recalc函数中检查表单是否有效,如下所示:
function recalc(){
if($('#items').valid()) {
// the form is valid - continue
$("[id^=total_item]").calc(
// the equation to use for the calculation
"qty * price",
// define the variables used in the equation, these can be a jQuery object
{
qty: $("input[name^=qty_item_]"),
price: $("[id^=price_item_]")
},
// define the formatting callback, the results of the calculation are passed to this function
function (s){
// return the number as a dollar amount
return "$" + s.toFixed(2);
},
// define the finish callback, this runs after the calculation has been complete
function ($this){
// sum the total of the $("[id^=total_item]") selector
var sum = $this.sum();
$("#grandTotal").text(
// round the results to 2 digits
"$" + sum.toFixed(2)
);
}
);
} else {
// the form is invalid - do nothing
}
}