使用javascript启用/禁用嵌套表单字段

时间:2013-02-03 16:12:34

标签: javascript ruby-on-rails

我有一个带有复选框和文本字段的嵌套表单。我希望只有在单击/启用该特定嵌套表单的文本框时才能启用文本字段。如果设置了“自定义”文本框,则当前硬编码为启用/禁用字段。如何让javascript动态更新这些文本框属性?

现在Form.erb

<%= simple_nested_form_for @client do |f| %>
  <%= f.fields_for :client_prices do |def_price_form| %>
  <div class="controls controls-row">
    <div class='span10'>
      <% if def_price_form.object.custom == true  %>
        <%= def_price_form.input :custom, :wrapper_html => { :class => 'span1' } %>
        <% end %>
        <%= def_price_form.input :visit_type, :wrapper_html => { :class => 'span2' } %>
        <%= def_price_form.input :price, :wrapper => :prepend, :wrapper_html => { :class => 'span2' }, :label => "Price" do %>
          <%= content_tag :span, "$", :class => "add-on" %>
          <%= def_price_form.input_field :price %>
          <%= def_price_form.link_to_remove '<i class="icon-remove"></i>'.html_safe, :class => 'btn btn-danger', :wrapper_html => { :class => 'span3 pull-left' } %>
          <%end%>
      <% else %>
        <%= def_price_form.input :custom, :hidden => false, :wrapper_html => { :class => 'span1' } %>
        <%= def_price_form.input :visit_type, disabled: true,  :wrapper_html => { :class => 'span2' } %>
        <%= def_price_form.input :price, :wrapper => :prepend, :wrapper_html => { :class => 'span2' }, :label => "Price" do %>
          <%= content_tag :span, "$", :class => "add-on" %>
          <%= def_price_form.input_field :price, disabled: true %>
          <%end%>
      <%end%>
    </div>
  </div>
  <% end %>
  <%= f.link_to_add "Add a custom price", :client_prices, :class => 'btn btn-success' %>
  <p>&nbsp;</p>
  <div class="controls">
    <%= f.button :submit, :class => 'btn btn-primary' %>
  </div>
<% end %>

RoR在这里生成的HTML http://jsfiddle.net/59AXJ/

2 个答案:

答案 0 :(得分:1)

这将从单击的复选框中获取属性名称。然后找到具有相似名称的输入,这些是我们将切换为“禁用”的输入。

$("input[type='checkbox']").click(function () {
    var thisCheckbox = $(this);
    var id = $(this).attr("id");
    var text = $("label[for=" + id + "]").text().toLowerCase();
    var name = $(this).attr("name").replace("[" + text + "]", "");
    $("input[name*='" + name + "']").each(function () {
        var thisInput = $(this);
        if (thisInput.attr("disabled")) {
            thisInput.removeAttr("disabled");
        } else {
            thisInput.attr("disabled", "disabled");
            thisCheckbox.removeAttr("disabled");
        }
    })
});

http://jsfiddle.net/Sbw65/&lt; - 测试出来

答案 1 :(得分:0)

据我所知,这是不可能的,但你可以在javascript上编写一些独特的函数,它会通过css类将一些输入与一些复选框连接起来。像这样的东西(CoffeeScript上的代码):

changeCheckbox: (class_value) =>
  $('[type=checkbox] '+class_value)). on 'check', (e) ->
    $input = $(e.currentTarget)
      if !$input.prop("checked")
        $("input "+class_value).prop('disabled', false)
      else
        $("input "+class_value).prop('disabled', true)

之后,您只需要为连接的复选框和输入添加一些类。

相关问题