2012-12-23 28 views
3

我想在用戶從日期選擇器彈出窗口中選擇一個日期(或者對該事件做出任何更改,無論是日期還是時間)時自動保存表單。在導軌中,我使用:remote => true的表單來簡單地更改截止日期屬性。這只是一個領域,所以讓用戶在選擇日期後點擊「提交」按鈕,感覺有點過火。我目前已經設置了在用戶更新表單時使用AJAX顯示更新的日期,但是,我希望在沒有實際點擊提交按鈕的情況下完成此操作。Rails&jQuery Datepicker - 選擇日期時保存表格

這裏是我的ERB:

<%= form_for todo, :remote => true, :url => update_todo_project_path, :html => {:id => "todo#{todo.id}" } do |f| %> 
    <%= f.hidden_field :id %> 
    <%= f.text_field :due %> 
    <%= f.submit %> 
<% end %> 

使用Javascript(只是一個外部的js文件):

$('input#project_todo_due').datetimepicker({ 
    dateFormat: 'yy-mm-dd', 
    timeFormat: 'hh:mm' 
}); 

而update_todo.js.erb:

$("#dueon<%= @todo.id%>").html("<%= raw escape_javascript(render(:partial => 'duedate')) %>"); 

回答

3

我要採取刺傷它:我用

$('input#project_todo_due').datetimepicker({ 
    dateFormat: 'yy-mm-dd', 
    timeFormat: 'hh:mm', 
    onClose: function(strDate, datepicker) { 
    // According to the docs this situation occurs when 
    // the dialog closes without the user making a selection 
    if(strDate == "") { 
     return; 
    } 

    // According to the docs this refers to the input 
    // Some digging in jquery-ujs on github make it 
    // look like triggering the 'submit.rails' event 
    // on the form will cause the normal unobtrusive 
    // js helpers to post the form. 
    // What's not clear is if the input element has the 
    // updated value at this point. 
    $(this).parent().trigger('submit.rails') 
    } 
}); 

文檔:

jQuery UI Datepicker -- onClose

jquery-ujs on Github -- relevant lines begin at 362

+0

難以置信。它工作完美。驚人的4行代碼可以做到。非常感謝帕特里克! –