Dango Dango - 3 months ago 10
jQuery Question

Rails display datetime in text field

Have a _form.html.erb in which I want to display datetime in a text field instead of a dropdown menu. My code below does not display anything in my text field, how do I go about this...

<div class="field">
<%# f.label :time %>
<%# f.datetime_select :time %>
<%= f.text_field:time, :value => timesheet.user, :readonly => true %>
</div>


Illustration below

rails datetime into text field with datetime

After @luissimo mentioned javascript I came up with a snipplet of code in jquery

var tm1 = $( "#timesheet_time_1i" ).val();
var tm2 = $( "#timesheet_time_2i" ).val();
var tm3 = $( "#timesheet_time_3i" ).val();
var tm4 = $( "#timesheet_time_4i" ).val();
var tm5 = $( "#timesheet_time_5i" ).val();
var tm_all = tm1 + '-'+ tm2 + '-' + tm3 + ' ' + tm4 + ':' + tm5;

$('#timesheet_time').val(tm_all);

Answer

First change your code to this;

<div class="field">
<%# f.label :time %>
<%# f.datetime_select :time %>
<p class="output_time"></p>
</div>

Then find the id's of your datetime_select which are predefined by Rails. Find it by using inspect element. I will call the id's #id1 to #id5 just for explanation purposes.

Then in jQuery do something like this;

$(".output_time").text( ($("#id3").val()) + ' ' + ($("#id2").find(":selected").text()) + ' ' +  ($("#id1").val()) );

$("#id3").change(function()
{
  $('.output_time').text( ($(this).val()) + ' ' + ($("#id2").find(":selected").text()) + ' ' +  ($("#id1").val()) ) ;
});
$("#id2").change(function()
{
  $('.output_time').text( ($("#id3").val()) + ' ' + ($(this).find(":selected").text()) + ' ' + ($("#id1").val()) ) ;
});
$("#id1").change(function()
{
  $('.output_time').text( ($("#id3").val()) + ' ' + ($("#id2").find(":selected").text()) + ' ' + ($(this).val()) ) ;
});

I used 3 id's here but you have 5 so you can just add those behind it, that way you can even learn some jQuery and make your own output format(DD-MM-YY-TT etc..).