【问题标题】:Dynamically change radio button with select (Ruby on Rails)使用选择动态更改单选按钮(Ruby on Rails)
【发布时间】:2020-05-19 22:06:27
【问题描述】:

我是编程新手,尤其是 Rails。 我有一个创建新目标记录的表格。 我可以选择目标“地平线”:“每周”、“每季度”或“每年” 我还有一个单选按钮“截止日期”,用于设置本学期或下学期的目标(例如,在每周目标的情况下:本周或下周)。

我想做的是:根据select的selected选项动态更新单选按钮。

<%= form_with(model: @goal, url: goals_path, id: "new-goal-form", local: true) do |f| %>
  <p><%= @goal.errors[:date].first %></p>
  <div class="field">
    <label class="label">Title</label>
    <div class="control">
      <%= f.text_field :title, class: "input"%>
    </div>
    <p><%= @goal.errors[:title].first %></p>
  </div>
  <div class="field">
    <label class="label">Description</label>
    <div class="control">
      <%= f.text_area :description, class: "textarea"%>
    </div>
  </div>
  <div class="field">
    <label class="label">Horizon</label>
    <div class="control">
      <div class="select">
        <%= f.select :horizon, options_for_select({"Weekly" => "week", "Quarterly" => "quarter", "Yearly" => "year"}, @horizon), include_blank: true %>
      </div>
    </div>
  </div>

  <div class="field">
    <label class="label">Due Date</label>
    <div class="control">
      <%= f.radio_button :date, DateTime.current.to_date.end_of_week.strftime('%Y-%m-%d'), :checked => true, id:"radio-this", class: "is-checkradio" %>
      <label for="radio-this">
        This <%= @horizon.capitalize %>
      </label>
      <%= f.radio_button :date, 1.week.from_now.to_date.end_of_week.strftime('%Y-%m-%d'), id:"radio-next", class: "is-checkradio" %>
      <label for="radio-next">
        Next <%= @horizon.capitalize %>
      </label>
    </div>
  </div>
  <div class="field">
    <label class="label">Related goal</label>
    <div class="control">
      <div class="select">
        <%= f.select :related_goal_id, options_from_collection_for_select(@related_goal, 'id', 'title'), include_blank: true %>
      </div>
    </div>
  </div>
  <br/>
  <div class="field is-grouped">
    <div class="control">
      <%= f.submit "Save", class: "button is-primary" %>
    </div>
    <div class="control">
      <%= link_to "Cancel", goals_path(horizon: @horizon), class: "button" %>
    </div>
  </div>
<% end %>

我尝试在选择的末尾添加 :onchange,但更改所选选项时实际上没有任何反应。

非常感谢。

【问题讨论】:

  • 所以你想...更新单选按钮以依赖于选择选项。为什么不直接使用纯 JavaScript 并通过点击事件处理?

标签: ruby-on-rails


【解决方案1】:

您的单选按钮是否有不同的标识?它们似乎都具有相同的自动生成 ID。这在javascript中不起作用。在下方,您为选择框设置了一个点击事件,根据选择的子项,您将一个单选按钮设置为选中。

$(document).ready(function(){
   //when select option is chosen, set radio button to selected.
   $("#select").click(function(){
       var option = $(this).children("option:selected").val()
        if(option == "weekly"){
           $("#radio_button_weekly").prop("checked", true);
        }
    )}
)};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多