簡體   English   中英

如何將jQuery Datepicker連接到Ruby on Rails表單?

[英]How do I connect jQuery Datepicker to my Ruby on Rails form?

我正在嘗試使用jQuery Datepicker在我的Ruby on Rails表單中設置日期字段,但我無法弄清楚如何做到這一點。 有人能指出我正確的方向嗎?

我已經構建了一個gem來處理這個:

https://github.com/albertopq/jquery_datepicker

希望它能幫助別人。

Ryan Bates對這一切有一個非常好的解釋:

http://railscasts.com/episodes/213-calendars (舊版本,你可以免費觀看) http://railscasts.com/episodes/213-calendars-revised (修訂版你需要訂閱觀看)

截至目前,我建議jquery-ui-rails gem高於其他答案,原因很簡單,你可以只包含datepicker資源而不需要整個jquery ui庫!

https://github.com/joliss/jquery-ui-rails

我使用albertopq提到的albertopq的jquery_datepicker,它適用於常規表單,嵌套屬性等。這讓我很容易。 jquery_datepicker也正確地將選項傳遞給datepicker必要的javascript調用。

以下是我的一個嵌套表單中的示例:

<%= f.datepicker 'availability', :minDate => 0, :maxDate => "+8Y", :tab_index => autotab %>

minDate和maxDate傳遞給datepicker,tab_index被放入文本字​​段html。 (autotab只是我的表單助手,可以推進標簽+ 1 ...對我來說比硬編碼更好)。

Rails 5.x的更新

步驟1.安裝jquery-ui-rails gem

# gemfile
gem 'jquery-ui-rails'

# app/assets/javascripts/application.js
//= require jquery-ui/widgets/datepicker

# app/assets/stylesheets/application.css
*= require jquery-ui/datepicker

步驟2.假設您有一個名為Event的資源,其日期或日期時間字段名為:start,然后在表單中將:start字段設為文本字段。

# app/views/events/_form.html.erb
<%= f.label :start, 'Start Date' %>
<%= f.text_field :start %>

步驟3.添加Javascript(在此處使用CoffeeScript語法)。 Line1)如果你啟用了Turbolinks(Turbolinks通過加載AJAX來點擊鏈接時加速Rails頁面加載)你需要添加一個包裝器,或者從內部鏈接導航到頁面時不會加載JavaScript函數。

Line2)您正在定位表單中的元素ID。 Rails通過組合模型名稱和字段名稱自動為表單輸入分配id。

Line3)您需要設置dateFormat,因為jQuery-UI和Rails使用不同的默認日期格式。

# app/assets/javascripts/event.coffee
$(document).on 'turbolinks:load', ->
  $('#event_start').datepicker
    dateFormat: 'yy-mm-dd'

對於Rails 4,除了JavaScript(或Cof​​feeScript)文件中的第一行外,一切都是相同的。 在Rails 4中啟用Turbolinks時加載JavaScript的包裝器是:

$(document).on "page:change", ->

可能有點晚了,但我使用了一個簡單的寶石:

Gemfile:gem'jquery gem 'jquery-ui-rails'

Application.js: //= require jquery-ui

Application.css *= require jquery-ui

然后: Bundle install

資料來源: https//github.com/joliss/jquery-ui-rails

如果使用Rails 3.0+,除了包含jQuery和jQuery UI之外,您不需要做任何事情,因為jQuery是默認的JavaScript框架。

如果使用早於3.0的Rails或使用Prototype(或其他),則需要在noConflict模式下使用jQuery。 確保在使用類似的東西加載Prototype(您的其他框架)之后包含jQuery:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jqueryui.js"></script>
<script type="text/javascript">
  jQuery.noConflict();
  jQuery(document).ready(function($) {
    // here the $ function is jQuery's because it's an argument
    // to the ready handler
    $('#dateField').datepicker();
  });
  // here the $ function is Prototype's
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM