Last active
August 29, 2015 14:05
-
-
Save jtangelder/6a331c42672c82403efc to your computer and use it in GitHub Desktop.
input[type="calc"]
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
<!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