Skip to content

Instantly share code, notes, and snippets.

@sebald
Created October 2, 2012 13:38
Show Gist options
  • Select an option

  • Save sebald/3819245 to your computer and use it in GitHub Desktop.

Select an option

Save sebald/3819245 to your computer and use it in GitHub Desktop.
Function to only allow decimal input
if(typeof isDecNumber != 'function'){
window.isDecNumber = function(e) {
// backspace, tab, enter, end, home, left, right
// we don't support the del key in Opera because del == . == 46.
var controlKeys = [8, 9, 13, 35, 36, 37, 39, 46]
// IE doesn't support indexOf
var isControlKey = controlKeys.join(",").match(new RegExp(e.which))
// some browsers just don't raise events for control keys. Easy.
// e.g. Safari backspace.
if (!e.which || // control keys in most browsers. e.g. Firefox tab is 0
(48 <= e.which && e.which <= 57) || // always 1 through 9
(96 <= e.which && e.which <= 105) || // always 1 through 9 (number block)
(188 == e.which) || (190 == e.which) || (110 == e.which) || // allow comma and dot
isControlKey) { // Opera assigns values for control keys.
// no leading 0
if( (48 == e.which || 96 == e.which) &&
(e.target.selectionStart < 1) )
e.preventDefault()
// only allow one comma and/or dot
if( (188 == e.which || 190 == e.which || 110 == e.which) &&
( (e.target.value.indexOf(",") >= 0) ||
(e.target.value.indexOf(".") >= 0) )
)
e.preventDefault()
return true
} else {
e.preventDefault()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment