PDA

View Full Version : [JavaScript] Increment Buttons



nathj07
11-19-2007, 09:33 AM
1) CODE TITLE: JavaScript Spinner Control

2) AUTHOR NAME/NOTES: Nathan Davies

3) DESCRIPTION: This allows users of your site to click buttons to increment numeric values. this functions just like the spinner control available in many desktop programming languages

4) URL TO CODE:


function setQuantity(pcID, pnOperation, pnMin, pnMax)
{
var lnCurrentQuantity = parseInt(document.getElementById(pcID).value);
var lnNewQuantity = lnCurrentQuantity ;
switch(pnOperation)
{
case 1: // increase quantity by 1
lnNewQuantity++ ;
if(lnNewQuantity > pnMax)
{
lnNewQuantity = lnCurrentQuantity ;
}
break;
case 2:// decrease quantity by 1
lnNewQuantity-- ;
if(lnNewQuantity < pnMin)
{
lnNewQuantity = lnCurrentQuantity ;
}
break;
default:// ensuring a typed quantity remains within the parameters defined
if (lnCurrentQuantity > pnMax || lnCurrentQuantity < pnMin)
{
alert("Please set the quantity as a number between " + pnMin + " and " + pnMax + '\n' + "The quantity will now be set to " + pnMin) ;
lnNewQuantity = pnMin ;
}
break;
}

document.getElementById(pcID).value = lnNewQuantity ;
}
To use it simply call it on the onclick event of a button or image that indicates plus or minus. Here's an example using an image


<!-- reduce quantity -->
<img src="image/minus.png" alt="minus" title="Decrease Quantity" onmouseover="this.style.cursor=\'pointer\';" onclick="setQuantity(\'dataQuantity\', 2, 1, 6);"/>
<!-- the input box -->
<input class="quantity" type="text" id="dataQuantity" name="dataQuantity" value=1 onblur="setQuantity(\'dataQuantity\', 3, 1, 6);"/>
<!-- increase quantity -->
<img src="image/plus.png" alt="plus" title="Increase Quantity" onmouseover="this.style.cursor=\'pointer\';" onclick="setQuantity(\'dataQuantity\', 1, 1, 6);"/>


I use a simple picture of a plus sign and minus sign for the images - easily created in any image software.

The parameters are the ID of the control that stores the value, the type of change - 1 = plus 1 2 = minus 1 and 3=user entered value (use when calling the function via onblur), the minimum value allowed and the maximum value allowed. In the example above the minimum is 1 and the maximum is 6