我使用以下代码创建带有+和 - 符号的按钮来增加或减少值。它工作正常,但我需要设置一个限制,如果数字的总值等于5,它将不会让你再增加。
HTML:
<div id="page-wrap">
<h1>Input Number Incrementer</h1>
<form method="post" action="">
<div class="numbers-row">
<label for="name">French Hens</label>
<input type="text" name="french-hens" id="french-hens" value="0">
</div>
<div class="numbers-row">
<label for="name">Turtle Doves</label>
<input type="text" name="turtle-doves" id="turtle-doves" value="0">
</div>
<div class="numbers-row">
<label for="name">Partridges</label>
<input type="text" name="partridge" id="partridge" value="0">
</div>
<div class="buttons">
<input type="submit" value="Submit" id="submit">
</div>
</form>
</div>
Jquery的:
$(function() {
$(".numbers-row").append('<div class="inc button">+</div><div class="dec button">-</div>');
$(".button").on("click", function() {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input").val(newVal);
});
});
答案 0 :(得分:1)
请参阅: DEMO
$(function () {
$(".numbers-row").append('<div class="inc button">+</div><div class="dec button">-</div>');
$(".button").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input").val();
var sum = 0;
$('.numbers-row input[type="text"]').each(function () {
sum += Number($(this).val());
});
if ($button.text() == "+" && sum < 5) {
var newVal = parseFloat(oldValue) + 1;
} else if ($button.text() == "-") {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
} else {
return false;
}
$button.parent().find("input").val(newVal);
});
});
答案 1 :(得分:0)
在本节中添加以下内容:
if ($button.text() == "+") {
if (parseFloat(oldValue) <= 5) {
var newVal = parseFloat(oldValue) + 1;
}
}