Skip to content

Instantly share code, notes, and snippets.

@nsa-yoda
Created March 20, 2013 19:34
Show Gist options
  • Save nsa-yoda/5207739 to your computer and use it in GitHub Desktop.
Save nsa-yoda/5207739 to your computer and use it in GitHub Desktop.
A dirty javascript function to calculate a new price based on a given price per number of items list.
<script text='text/javascript'>
// function to calculate and update based on price and number of items
function updateInpPrice(val){
if(!val || isNaN(val) || val == 0) val = 1;
val = Math.floor(Math.ceil(val));
var js_prices = [{"bounds":{"lowerBound":51,"upperBound":100},"price":"65.9900"},{"bounds":{"lowerBound":26,"upperBound":50},"price":"69.9900"},{"bounds":{"lowerBound":11,"upperBound":25},"price":"74.9900"},{"bounds":{"lowerBound":1,"upperBound":10},"price":"79.0000"}];
var lenv = js_prices.length - 1;
var iter = 0;
var base = document.getElementById("inp-price");
var multiplier = 1;
var upper = 0;
var quote = 0;
if(isNaN(val) == true)
base.innerHTML = "$" + (~~js_prices[iter]['price']).toFixed(2);
else {
while(iter <= lenv){
if(js_prices[iter]['bounds']['upperBound'] > upper)
upper = js_prices[iter]['bounds']['upperBound'];
if(val >= upper + 1)
quote = "Quote";
if(val <= js_prices[iter]['bounds']['upperBound'] &&
val >= js_prices[iter]['bounds']['lowerBound']){
multiplier = js_prices[iter]['price'];
}
iter += 1;
}
base.innerHTML = (quote ? quote : "$" + (multiplier * val).toFixed(2));
}
quote = 0;
return false;
}
</script>
<div class="inp">
QUANTITY:
<input type="text" name="qty" class="inp-qty" onkeyup="javascript:updateInpPrice(this.value)" onblur="javascript:updateInpPrice(this.value)" />
<span class="inp-price" id="inp-price">$589.99</span>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment