Skip to content

Instantly share code, notes, and snippets.

@jtangelder jtangelder/example
Last active Aug 29, 2015

Embed
What would you like to do?
input[type="calc"]
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>input[type="calc"]</h1>
<p>Usable for complicated input that require a calculator.</p>
<p>
<input type="calc" placeholder="Supports calculations, eg: (5 * 5 + 100) / 5" size="100">
</p>
<p>
<input type="text" placeholder="Normal text input" size="100">
</p>
<script>
(function() {
function inputCalc(ev) {
var el = ev.target;
if(!(el.nodeName == 'INPUT' && el.getAttribute('type') == 'calc')) {
return;
}
var val = el.value
.replace(/,/g, '.') // replace commas with dots
.replace(/[a-z]/gi, ''); // simple sanitizing to remove JS calls
try {
var result = new Function('return '+ val)();
if(!isNaN(result)) {
el.value = result;
} else {
throw new Error('Result is not a number.');
}
} catch(err) {
el.value = el.defaultValue;
}
}
window.addEventListener("blur", inputCalc, true);
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.