Force an input to be numeric with jQuery


/ Published in: JavaScript
Save to your folder(s)

This tiny jQuery plug in forces a user to enter only numeric values on an input field by silently removing non-numeric values as they're entered. (Caution: Never rely on client-side validation; use server-side validation as well)


Copy this code and paste it in your HTML
  1. (function ($) {
  2. $.fn.forceNumeric = function () {
  3. return this.each(function () {
  4.  
  5. $(this).keyup(function() {
  6. if (!/^[0-9]+$/.test($(this).val())) {
  7. $(this).val($(this).val().replace(/[^0-9]/g, ''));
  8. }
  9. });
  10. });
  11. };
  12. })(jQuery);
  13.  
  14. // Usage example: $('input.numeric').forceNumeric();

URL: http://terraduo.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.