In some cases we need to create some kind of online calculator without sending information to server. There are a lot of plugins but they are usefull only if we need to make serious calculations in simple cases we can use our brain and jQuery api. Code given below consist of two parts: html and js.
So html we need given below:
<div id="price_form"> <div class="calc_description"><span>Calculator</span>calculate something</div> <form> <div class="price_selection"> <label>Some select list</label> <select id="price_calculator"> <option value="50">First option</option> <option value="55">Second option</option> <option value="70">Third option</option> <option value="125">Fourth option</option> <option value="115">Fifth option</option> <option value="125">Sixth option</option> <option value="195">Seventh option</option> </select> </div> <div class="width_selection"> <label>Width in (m)</label> <input type="text" id="width" name="Width" value="" size="15" maxlength="25" class="form-text"> </div> <div class="height_selection"> <label>Height in (m)</label> <input type="text" id="height" name="Height" value="" size="15" maxlength="25" class="form-text"> </div> </form> <div id="price">Total amount (usd):<span id="price_value">0 usd</span></div> </div>
Its our html layout. Lets talk about it. It consists of one select list and two inputs (width and height). While user select option in select list he select multiplier of total ammount. The multiplier is stored in value attribute.
Lets look at our js part.
$('#price_calculator').change(function(){ var price = $(this).attr('value'); var width = $('#price_form input[id="width"]').attr('value'); var height = $('#price_form input[id="height"]').attr('value'); if (isNaN(width)) { alert("Enter width correct numerical value"); } if (isNaN(height)) { alert("Enter height correct numerical value"); } var tot = (price*width*height); if(isNaN(tot) ) { $('span#price_value').html(0+" usd"); } else { $('span#price_value').html(tot.toFixed(2)+" usd"); } }); $('#price_form input[id="width"], #price_form input[id="height"]').keyup(function(){ var price = $('#price_calculator :selected').attr('value'); var width = $('#price_form input[id="width"]').attr('value'); var height = $('#price_form input[id="height"]').attr('value'); if (isNaN(width)) { alert("Enter width correct numerical value"); } if (isNaN(height)) { alert("Enter height correct numerical value"); } var tot = (price*width*height); if(isNaN(tot) ) { $('span#price_value').html(0+" usd"); } else { $('span#price_value').html(tot.toFixed(2)+" usd"); } });
I should mention that this code make simple validation of entered values and check if they are numerical. So thats all continue doing Drupal!