/*
*
* Copyright (c) 2006/2007 Sam Collett (http://www.texotela.co.uk)
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
* 
* Version 1.0
* Demo: http://www.texotela.co.uk/code/jquery/numeric/
*
* $LastChangedDate$
* $Rev$
*/
/*
* Allows only valid characters to be entered into input boxes.
* Note: does not validate that the final text is a valid number
* (that could be done by another script, or server-side)
*
* @name numeric
* @param decimal Decimal separator (e.g. '.' or ',' - default is '.')
* @param callback A function that runs if the number is not valid (fires onblur)
* @author Sam Collett (http://www.texotela.co.uk)
* @example $(".numeric").numeric();
* @example $(".numeric").numeric(",");
* @example $(".numeric").numeric(null, callback);
*
*/
jQuery.fn.numeric = function(decimal, callback)
{
decimal = decimal || ".";
callback = typeof callback == "function" ? callback : function(){};
this.keypress(
function(e)
{
var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
if(key == 13 && this.nodeName.toLowerCase() == "input")
{
return true;
}
else if(key == 13)
{
return false;
}
var allow = false;
if((e.ctrlKey && key == 97 /* firefox */) || (e.ctrlKey && key == 65) /* opera */) return false;
if((e.ctrlKey && key == 120 /* firefox */) || (e.ctrlKey && key == 88) /* opera */) return false;
if((e.ctrlKey && key == 99 /* firefox */) || (e.ctrlKey && key == 67) /* opera */) return false;
if((e.ctrlKey && key == 122 /* firefox */) || (e.ctrlKey && key == 90) /* opera */) return false;
if((e.ctrlKey && key == 118 /* firefox */) || (e.ctrlKey && key == 86) /* opera */
|| (e.shiftKey && key == 45)) return false;
if(key < 48 || key > 57)
{
/* '-' not allowed */
if(key == 45 ) return false;
/* only one decimal separator allowed */
if(key == decimal.charCodeAt(0) && this.value.indexOf(decimal) != -1)
{
allow = false;
}
if(
key != 8 /* backspace */ &&
key != 9 /* tab */ &&
key != 13 /* enter */ &&
key != 35 /* end */ &&
key != 36 /* home */ &&
key != 37 /* left */ &&
key != 39 /* right */ &&
key != 46 /* del */
)
{
allow = false;
}
else
{
if(typeof e.charCode != "undefined")
{
if(e.keyCode == e.which && e.which != 0)
{
allow = true;
}
else if(e.keyCode != 0 && e.charCode == 0 && e.which == 0)
{
allow = true;
}
}
}
if(key == decimal.charCodeAt(0))
{
allow = false;
}
}
else
{
allow = true;
}
return allow;
}
)
.blur(
function()
{
var val = jQuery(this).val();
if(val != "")
{
var re = new RegExp("/^\d+$");
if(!re.exec(val))
{
callback.apply(this);
}
}
}
);
return this;
}