Rails将两个表单字段合并为一个

时间:2014-06-27 14:32:06

标签: javascript ruby-on-rails coffeescript

如何在提交前将日期和时间合并为“start_time”变量(和“end_time”)? JS?

 <%= form_for @task do |f| %>
        <%= render 'shared/error_messages', object: f.object %>
          <div class="time_selectors">
            <%= f.label :start_time %>
            <%= f.text_field :start_time, :class => 'datepicker' %>
            <select class="form-control time_dropdown" id="start_hour">
              <option>Select Date</option>
            </select>
            <div class="clear_both"></div>
            <%= f.label :end_time %>
            <%= f.text_field :end_time, :class => 'datepicker' %>
            <select class="form-control time_dropdown" id="end_hour">
              <option>Select Date</option>
            </select>
            </div>
            <div class="clear_both"></div>
          </div>
          <div class="clear_both"></div>
          <%= f.submit "Create Task", class: "btn btn-large btn-primary" %>
        </div>
    <% end %>

我将它们组合在我的任务模型中,如果可以,我宁愿将它们合并。

我的JS现在不起作用。我错过了什么?

$('#new-task').submit ()->
  valuesToSubmit = $(this).serialize
  console.log('test')
  console.log(valuesToSubmit)
  return false
$('button').click ()->
  console.log ('test2')

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?

$('form').on 'submit', (event) ->
    event.preventDefault()
    start_time = ''
    start_time += $(@).find('input[name=start_day]').val()
    start_time += '_'
    start_time += $(@).find('input[name=start_hour]').val()
    $('<input/>', {type: 'hidden', name: 'start_time', value: start_time}).appendTo($(@))
    @submit()

(* CoffeeScript版本尚未经过测试 - 请使用工作小提琴作为指导。)

Fiddle