Jquery-ui datepicker only appears after textbox fo

2019-08-07 04:37发布

问题:

For some reason, when I load the partial and I click the textbox to bring up the datepicker I have to click out of the textbox then click back in the textbox before the datepicker appears. Can anyone see anything wrong or how to fix it so the datepicker appears the first time the textbox is clicked? I'm using ruby 1.9.3 and rails 3.2.8

users.js.coffeescript

$("form[data-update-target]").live "ajax:success", (evt, data) ->
  target = $(this).data("update-target")
  $("#" + target).html data

$("#update-container").on 'click', '#event_start_at_date', (evt) ->
  $("#event_start_at_date").datepicker({ dateFormat: "yy-mm-dd" })

$("#update-container").on 'click', '#event_end_at_date', (evt) ->
  $("#event_end_at_date").datepicker({ dateFormat: "yy-mm-dd" })

_event partial the textbox is in

<%= form_for(@event) do |f| %>
  <div class="field">
  <%= f.label 'start date' %>*
  <%= f.text_field :start_at_date, :class => 'start_at_date', :size => 10, :maxlength => 10 %> 
  <%= f.text_field :start_at_time, :size => 5, :maxlength => 5 %>
</div>
<div class="field">
  <%= f.label 'end_date' %>*
  <%= f.text_field :end_at_date, :class => 'end_at_date', :size => 10, :maxlength => 10 %> 
  <%= f.text_field :end_at_time, :size => 5, :maxlength => 5 %>
</div>
<% end %>

new page for users new.html.erb

<%= form_tag({:controller => 'users', :action => 'preview'}, :remote => true, :'data-update-target' => 'update-container') do %>
  <%= radio_button_tag(:page_type, 'event', false, :class => 'submit') %>
  <%= label_tag(:page_type, "Event") %>
  <br/>
<% end %>
<div id="update-container">
</div>

回答1:

Calling

$("#event_start_at_date").datepicker({ dateFormat: "yy-mm-dd" })

doesn't open the datepicker, it just binds the datepicker to that element, which means that it will then react to clicks and open the datepicker.

You should bind datepickers to the elements when the DOM is loaded, not in a click handler.