use jQuery to allow input numeric only.
like these number:
0.1
1.
3.0
.1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
(function ($) { var my_validate_plug_name = "myvalidate"; function MyJqValidate(element, options){ this.init(element, options); } MyJqValidate.prototype = { init: function (element, options) { var allowFilter = ["positiveNumber"]; var defaults = {filter_type: "positiveNumber", enterCallback: function (obj){}, valCallback: function (val){}}; this.element = element; this.settings = $.extend( {}, defaults, options ); if($.inArray( this.settings.filter_type, allowFilter) == -1) { return; } this[this.settings.filter_type].call(this); }, positiveNumber: function (){ var _this = this; this.element.keyup(function (e){ var code = e.keyCode || e.which; var txt = $(this).val(); var reg = /^(0*\.?[1-9]\d*|[1-9]+(\d*\.\d*)?)$/; if(reg.test(txt)){ callback.call(_this, e); return; } var numb = txt.match(/\d|\./g); if(numb == null) { $(this).val(""); callback.call(_this, e); return; } numb = numb.join(""); var str = ""; var f = true; for(var i=0; i<numb.length; i++){ var s = numb[i]; if (s=="."){ if (f) { str += s; f = false; } } else { str += s; } } $(this).val(str); callback.call(_this, e); }); function callback(e){ this.value = $.trim(this.element.val()); var v = parseFloat(this.value); this.format_value = isNaN(v) ? 0 : v; this.settings.valCallback(this.format_value); var code = e.keyCode || e.which; if(code == 13) { //Enter keycode this.settings.enterCallback(this.element); } } } } $.fn[my_validate_plug_name] = function(options){ var elt; if ( options instanceof Object || !this.data( "plugin_" + my_validate_plug_name ) ) { elt = new MyJqValidate( this, options ); this.data('plugin_' + my_validate_plug_name, elt); } else { elt = this.data( "plugin_" + my_dialog_plug_name ); } if (typeof(options) == "string" && options.length>0){ eval("elt."+options+"(this)"); } return this; } }( jQuery )); |
call like :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$(function (){ $("#positive_number").myvalidate({ filter_type: "positiveNumber", enterCallback: function (obj){ //enter key callback alert(parseFloat(obj.val())); }, valCallback: function (val){ //pressup callback, return value $("div").html(val); } }); $("#positive_number").focus(); }); |