Skip to content

Instantly share code, notes, and snippets.

@jtangelder
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtangelder/6a331c42672c82403efc to your computer and use it in GitHub Desktop.
Save jtangelder/6a331c42672c82403efc to your computer and use it in GitHub Desktop.
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