Calculator
Framework for a text-field calculator, using the number type input field. Uses jQuery to allow calculation to be done by pressing enter from a field.
by Brett
HTML
<form id="form" action="form_action.asp">
This: <input type="number" name="v1"><br>
Plus This: <input type="number" name="v2"><br><br>
<button type="button" onclick="calculate()">Calculate</button>
</form>
<p>Equals <span id="result"></span></p>
JavaScript
//Get values from fields and write to HTML
function calculate() {
var vals = document.getElementById("form").elements;
//Method supported by IE: parseFloat(vals[0].value)
//Ideal method (works in Chrome and Firefox): vals[0].valueAsNumber
var result = parseFloat(vals[0].value)+parseFloat(vals[1].value)
document.getElementById("result").innerHTML = result;
}
//Submit if enter pressed from field
$(function() {
$('form').each(function() {
$(this).find('input').keypress(function(event) {
//10 for iPhone Safari (supposedly); 13 for everything else
if(event.which == 10 || event.which == 13) {
calculate()
}
});
});
});