admin管理员组文章数量:1405636
I have a simple JS counter with two buttons (+ and -) that is used to tally people. Works fine, but it allows the user to go into the negative when decreasing the count. Probably a simple solution but not for me. Any help would be appreciated. Thanks.
JS
//Pax Counter
$(document).ready(function(){
//Count Function
$('#increase').click(function() {
$('#pax_count').val(function(i, val) { return val*1+1 });
});
$('#decrease').click(function() {
$('#pax_count').val(function(i, val) { return val*1-1 });
});
});
HTML
<input name="pax_count" type="text" class="pax_input_box" id="pax_count" value="0" >
<div id="pax_counter_container"><!-- open #pax_counter_container -->
<button id="increase" type="button" class="click_button" onTouchStart="EvalSound('audio3')"></button>
<button id="decrease" type="button" class="click_button" onTouchStart="EvalSound('audio3')"></button>
</div><!-- close #pax_counter_container -->
I have a simple JS counter with two buttons (+ and -) that is used to tally people. Works fine, but it allows the user to go into the negative when decreasing the count. Probably a simple solution but not for me. Any help would be appreciated. Thanks.
JS
//Pax Counter
$(document).ready(function(){
//Count Function
$('#increase').click(function() {
$('#pax_count').val(function(i, val) { return val*1+1 });
});
$('#decrease').click(function() {
$('#pax_count').val(function(i, val) { return val*1-1 });
});
});
HTML
<input name="pax_count" type="text" class="pax_input_box" id="pax_count" value="0" >
<div id="pax_counter_container"><!-- open #pax_counter_container -->
<button id="increase" type="button" class="click_button" onTouchStart="EvalSound('audio3')"></button>
<button id="decrease" type="button" class="click_button" onTouchStart="EvalSound('audio3')"></button>
</div><!-- close #pax_counter_container -->
Share
Improve this question
asked Jan 17, 2013 at 18:37
macericpetmacericpet
631 silver badge7 bronze badges
3 Answers
Reset to default 6You can use Math.max()
:
$("#pax_count").val(function(i, val) {
return Math.max(0, val - 1);
});
I simply modified your function to check and see if the value is greater than or equal to 0 before subtracting.
$(document).ready(function(){
//Count Function
$('#increase').click(function() {
$('#pax_count').val(function(i, val) { return val*1+1 });
});
$('#decrease').click(function() {
$('#pax_count').val(function(i, val) {
if(val*1>0){
return val*1-1;
}else{
return val;
}
});
});
Simply check if val is smaller 1
$('#decrease').click(function() {
$('#pax_count').val(function(i, val) { return val>=1?val*1-1:0 });
});
本文标签: javascriptPrevent a negative number in JS click counterStack Overflow
版权声明:本文标题:javascript - Prevent a negative number in JS click counter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744239906a2596739.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论