Reputation: 115
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
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
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
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
Reputation: 3574
You could do several things:
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