Last active
January 7, 2019 16:57
-
-
Save grekodev/37a9218baf11187096d9ef8a93c953ab to your computer and use it in GitHub Desktop.
javascript only numbers
This file contains hidden or 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
| <h2>jQuery input filter showcase</h2> | |
| <p><b>Supports:</b> Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.</p> | |
| <p><b>Compatibility:</b> Cross-browser and on mobile, IE 9+.</p> | |
| <p><b>Note:</b> There is also a <a href="https://jsfiddle.net/emkey08/zgvtjc51" target="_blank">pure JavaScript version</a> of this, jQuery isn't actually needed.</p> | |
| <table> | |
| <tr><td>Integer:</td><td><input id="intTextBox"></td></tr> | |
| <tr><td>Integer up to 1500:</td><td><input id="intLimitTextBox"></td></tr> | |
| <tr><td>Unsigned integer:</td><td><input id="uintTextBox"></td></tr> | |
| <tr><td>Hex integer:</td><td><input id="hexTextBox"></td></tr> | |
| <tr><td>Float:</td><td><input id="floatTextBox"></td></tr> | |
| <tr><td>Currency (two decimals):</td><td><input id="currencyTextBox"></td></tr> | |
| </table> | |
| <script> | |
| // FUENTE | |
| // https://stackoverflow.com/questions/469357/html-text-input-allows-only-numeric-input | |
| // https://jsfiddle.net/emkey08/tvx5e7q3 | |
| // Restricts input for each element in the set of matched elements to the given inputFilter. | |
| (function($) { | |
| $.fn.inputFilter = function(inputFilter) { | |
| return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() { | |
| if (inputFilter(this.value)) { | |
| this.oldValue = this.value; | |
| this.oldSelectionStart = this.selectionStart; | |
| this.oldSelectionEnd = this.selectionEnd; | |
| } else if (this.hasOwnProperty("oldValue")) { | |
| this.value = this.oldValue; | |
| this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd); | |
| } | |
| }); | |
| }; | |
| }(jQuery)); | |
| // Install input filters. | |
| $("#intTextBox").inputFilter(function(value) { | |
| return /^-?\d*$/.test(value); }); | |
| $("#intLimitTextBox").inputFilter(function(value) { | |
| return /^\d*$/.test(value) && (value === "" || parseInt(value) <= 1500); }); | |
| $("#uintTextBox").inputFilter(function(value) { | |
| return /^\d*$/.test(value); }); | |
| $("#hexTextBox").inputFilter(function(value) { | |
| return /^[0-9a-f]*$/i.test(value); }); | |
| $("#floatTextBox").inputFilter(function(value) { | |
| return /^-?\d*[.,]?\d*$/.test(value); }); | |
| $("#currencyTextBox").inputFilter(function(value) { | |
| return /^-?\d*[.,]?\d{0,2}$/.test(value); }); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment