Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a negative number in JS click counter

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 -->
like image 907
macericpet Avatar asked Nov 19 '25 01:11

macericpet


2 Answers

You can use Math.max():

$("#pax_count").val(function(i, val) {
    return Math.max(0, val - 1);
});
like image 116
VisioN Avatar answered Nov 21 '25 14:11

VisioN


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;
         }
}); 

});
like image 28
Chris Sobolewski Avatar answered Nov 21 '25 13:11

Chris Sobolewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!