Alex
Alex

Reputation: 115

Stop js values going into negative

I have a problem with an increment function that allows users to press a button to add or remove tickets. However I don't want the user to be able to go into the negative's and screw everything up. Is there any way i can stop this from happening. A working demo can be found at http://kentishtours.co.uk/destinations/canterbury.php and the blue "-" "+" buttons are what i'm talking about.

Thanks

enter image description here

Code that is used to recognize input and increment the number.

var adult = $('#adult'),
child = $('#child'),
total = $('.total'),
value = $('#value'),
increase = $('#increase'),
decrease = $('#decrease'),
increasec = $('#increasec'),
decreasec = $('#decreasec');

var calulate_price = function(a, c){   
 var p1 = 18,
  p2 = 10,
  PA = a * p1,
  PC, d;

if(a >= 1) PC = c * p2;
else PC = c * p1;

d = PA + PC;

total.text("£ " + d + ".00");
value.val(d);
};

increase.click(function(){
var a = Number(adult.val());
var c = Number(child.val());  
adult.val(++a);
calulate_price(a, c);
}); 
decrease.click(function(){
var a = Number(adult.val());
var c = Number(child.val());  
adult.val(--a);
calulate_price(a, c);
}); 
increasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());  
child.val(++c);
calulate_price(a, c);
}); 
decreasec.click(function(){
var a = Number(adult.val());
var c = Number(child.val());  
child.val(--c);
calulate_price(a, c);
}); 

Upvotes: 1

Views: 6690

Answers (3)

NSjonas
NSjonas

Reputation: 12032

Disable the minus button if the value == 0

decrease = $('#decrease');

//set inital state
if(Number(adult.val())==0){
  $('#decrease').attr("disabled", "disabled");
}else{
  $('#decrease').removeAttr("disabled");
}

increase.click(function(){
  var a = Number(adult.val());
  adult.val(++a);
  //make sure its enabled any time we're > 0    
  if(a>0){
    $('#decrease').removeAttr("disabled");
  }
  var c = Number(child.val()); 
  calulate_price(a, c);
}); 
decrease.click(function(){
  var a = Number(adult.val());
  adult.val(--a);
  //disable if we are back to 0
  if(a==0){
    $('#decrease').attr("disabled", "disabled");
  }
  var c = Number(child.val());  
  calulate_price(a, c);
}); 

Upvotes: 3

MrJellyhands
MrJellyhands

Reputation: 159

decrease.click(function(){
  var a = Number(adult.val());
  var c = Number(child.val());
  if(a>0){
   adult.val(--a);
  }
  calulate_price(a, c);
}); 

Upvotes: 6

Rob
Rob

Reputation: 3574

You could do several things:

  • Disable the button when 0, so you cant go negative.
  • If the user posts a negative value, always take 0 (server side check)
  • If click on minus icon, and value is below 0, make it 0 again.

Just 3 possible options, I bet there are more left. ;)

Note, you always want to check the input server side, especially when it comes to money :)

Upvotes: 6

Related Questions