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 });
});
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744239906a4564655.html
评论列表(0条)