Skip to content

Instantly share code, notes, and snippets.

@richthegeek
Created February 15, 2012 15:23
Show Gist options
  • Save richthegeek/1836658 to your computer and use it in GitHub Desktop.
Save richthegeek/1836658 to your computer and use it in GitHub Desktop.
Number-input poly-fill (with optional added features)
$ = jQuery
jQuery.fn.number = (options) ->
defaults =
min: null
max: null
step: 1
pattern: /^(-?[0-9\.]*)$/
default_prefix: ''
default_suffix: ''
change_on_click: true
change_on_scroll: true
change_on_arrow: true
options = $.extend(defaults, options)
number_field_validate = (obj, num, val) ->
if ($(obj).attr('pattern') && !val.match(new RegExp($(obj).attr('pattern')))) || !val.match(options.pattern)
return 'match_error'
if ($(obj).attr('min') && num < parseInt($(obj).attr('min'), 10)) || (options.min && num < options.min)
return 'min_error'
if ($(obj).attr('max') && num > parseInt($(obj).attr('max'), 10)) || (options.max && num < options.max)
return 'max_error'
return true
return @each ->
$(this).data('number_old_value', $(this).val());
# scrolling
if options.change_on_scroll
$(this).mousewheel((e, delta, deltaX, deltaY) ->
step = (if delta < 0 then options.step * -1 else options.step)
val = $(this).val()
ma = val.match(/([^0-9\.\-]*)(-?[0-9\.]+)(.*)/)
if not ma then ma = ['', options.default_prefix, 0, options.default_suffix]
num = parseFloat(ma[2]) + step
val = ma[1] + num + ma[3]
$(this).val(val).keyup()
)
if options.change_on_click
$(this).click((e) ->
# get position within input...
input_pos = $(this).offset()
top = e.clientY - input_pos.top
left = e.clientX - input_pos.left
# get halfway mark (height) and width
height = $(this).outerHeight() / 2
width = $(this).outerWidth()
if left + 20 > width
if top < height
$(this).trigger('mousewheel', 1)
else
$(this).trigger('mousewheel', -1)
)
if options.change_on_arrow
$(this).keydown((e) ->
if e.keyCode? and e.keyCode == 38
return $(this).trigger('mousewheel', 1)
if e.keyCode? and e.keyCode == 40
return $(this).trigger('mousewheel', -1)
)
$(this).keyup((e) ->
val = $(this).val()
ma = val.match(/([^0-9\.\-]*)(-?[0-9\.]+)(.*)/)
if not ma
if val.length
ma = ['', options.default_prefix, 0, options.default_suffix]
else
return
num = parseFloat(ma[2])
val = ma[1] + num + ma[3]
validate = number_field_validate(this, num, val)
if validate == true
$(this).data('number_old_value', val).val(val)
else
$(this).trigger('invalid_input', validate)
$(this).val($(this).data('number_old_value'))
null
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment