Created
April 13, 2010 15:47
-
-
Save andywenk/364743 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using prototype.js | |
// There is a form with a lot of select fields: | |
/* | |
<form name="f" id="f" action="#"> | |
<input id="price_8" value="28.00" type="hidden"> | |
<select name="ticket_8" id="ticket_8" class="w50"> | |
<option value="0" label="0">0</option> | |
<option value="1" label="1">1</option> | |
</select> | |
<input id="price_9" value="4.00" type="hidden"> | |
<select name="ticket_9" id="ticket_9" class="w50"> | |
<option value="0" label="0">0</option> | |
<option value="1" label="1">1</option> | |
</select> | |
<input id="price_11" value="13.00" type="hidden"></td> | |
<select name="ticket_11" id="ticket_11" class="w50"> | |
<option value="0" label="0">0</option> | |
<option value="1" label="1">1</option> | |
<option value="2" label="2">2</option> | |
</select> | |
</form> | |
*/ | |
// At the bottom of the form is a field, where the sum is displayed. | |
// <span id="sum"><strong>12.50 EUR</strong></span> | |
// With the Form.Observer method, we can update this field each time a | |
// select field is changed. | |
new Form.Observer('f', 0.3, function(form, value){ | |
var tickets = value.split('&'), ticket, tick, amount, sum = 0; | |
// iterate over each element of teh object tickets | |
for(ticket in tickets) { | |
// Crockfor check for a for in loop ;-) | |
if(tickets.hasOwnProperty(ticket)) { | |
// just the form fields with id="ticket_" are interesting | |
if(!/(^ticket/).test(tickets[ticket])) continue; | |
// the form is ticket_n=value - we just need ticket_n | |
tick = tickets[ticket].replace(/=.*$/, ""); | |
// the hidden field with the price has the id price_n - so we simply | |
// change ticket_n to price_n and get the value | |
price = $(tick.replace(/ticket/, "price")).getValue(); | |
// the value of the select field | |
amount = $(tick).getValue(); | |
// now we can simply build the sum | |
sum += price * amount; | |
} | |
} | |
// update the field, where we show the total | |
$('sum').update('<strong>' + sum.toFixed(2) + ' EUR</span>'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment