Skip to content

Instantly share code, notes, and snippets.

@visnup
Created December 14, 2008 20:14
Show Gist options
  • Save visnup/35784 to your computer and use it in GitHub Desktop.
Save visnup/35784 to your computer and use it in GitHub Desktop.
Time select elements in rails use 0-23 for the hour. I'm used to 1-12 AM/PM.
#
# <%= form.select_time :start, :meridian => true %>
#
module ActionView
module Helpers
class DateTimeSelector
def select_time_with_meridian
html = select_time_without_meridian
if @options[:meridian]
id = input_id_from_type(:hour)
onchange = <<-EOS
if (this.value == 'AM') {
$A($('#{id}').options).each(function(o, i) {
o.value = i + 1;
if (o.value == 12) o.value = 0;
if (o.value < 10) o.value = '0' + o.value;
});
} else {
$A($('#{id}').options).each(function(o, i) {
o.value = i + 13;
if (o.value == 24) o.value = 12;
});
}
EOS
value = hour < 12 ? 'AM' : 'PM'
html += "<select onchange=\"#{onchange}\"><option#{' selected="selected"' if value == 'AM'}>AM</option><option#{' selected="selected"' if value == 'PM'}>PM</option></select>"
end
html
end
alias_method_chain :select_time, :meridian
def select_hour_with_meridian
if @options[:meridian]
if @options[:use_hidden] || @options[:discard_hour]
build_hidden(:hour, hour)
else
h = hour % 12
h = 12 if h == 0
html = build_options_and_select(:hour, h, :start => 1, :end => 12)
if hour < 12
html.gsub('value="12"', 'value="00"')
else
html.gsub(/value="(\d+)"/) do |match|
value = $1.to_i + 12
value = 12 if value == 24
"value=\"#{value}\""
end
end
end
else
select_hour_without_meridian
end
end
alias_method_chain :select_hour, :meridian
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment