【问题标题】:Show/Hide submit button depending on selected value根据所选值显示/隐藏提交按钮
【发布时间】:2015-05-13 08:31:26
【问题描述】:

我想根据表单中的选定值显示/隐藏其他提交按钮。
我没有使用 JavaScript 的经验,所以我只尝试修改网络上的示例。
不幸的是,我找不到与 rails form_for 相关的任何内容。
到目前为止,这是我尝试过的:

<%= form_for @discount, url: {action: "create"} do |f| %>
    <%= f.label :name, "Name" %><br />
    <%= f.text_field :name, placeholder: "Name" %><br />
    <%= f.label :description, "Description" %><br />
    <%= f.text_area :description, placeholder: "Description" %><br />
    <%= f.label :with_codes, "Type" %><br />
    <%= f.select :with_codes, [['Without Codes', false],['With Codes', true]], :selected => :with_codes %><br />

    <div id="row_dim">
        <%= f.submit "Manage Codes" %><br />
    </div>

      <script>
          $(function() {
              $('#row_dim').hide();
              $('#with_codes').change(function(){
                  if($('#with_codes').val() == true) {
                      $('#row_dim').show();
                  } else {
                      $('#row_dim').hide();
                  }
              });
          });
      </script>

    <%= f.submit "Draft" %>
    <%= f.submit "Save" %>
<% end %>

这个脚本只隐藏了我的提交按钮,但我认为在表单中识别选定的值存在问题。

【问题讨论】:

    标签: javascript ruby-on-rails forms


    【解决方案1】:

    首先:你确定选择的id是with_codes而不是discount_with_codes

    第二件事,您应该将选择的值作为字符串进行比较。考虑到这两个问题,下面的代码应该可以工作:

    <script>
       $(function() {
         $('#row_dim').hide();
         $('#discount_with_codes').change(function(){
           if($('#discount_with_codes').val() == 'true') {
             $('#row_dim').show();
           } else {
             $('#row_dim').hide();
           }
         });
       });
    </script>
    

    【讨论】:

    • 你是对的。我不知道该模型是 field_id 的一部分。谢谢你:)
    【解决方案2】:

    或者可能像这样(更简洁):

    $(function() {
      $("#row_dim").toggle($("#discount_with_codes").val() == 'true');
      $("#discount_with_codes").change(function() {
        $("#row_dim").toggle($(this).val() == 'true');
      });
    });
    

    编辑:哎呀,看来您已经接受了答案。但无论如何我都会把我的留在这儿。

    【讨论】:

    • 我认为您的解决方案更好。因为它不会在编辑表单中自动隐藏按钮。谢谢你:)
    • 你会得到与@pmichna 接受的答案相同的结果,只在$("#row_dim").hide() 周围添加条件。但他基本上完美地回答了你的问题(布尔值作为字符串),这就是它的全部内容。我的解决方案只是更紧凑一点;)
    【解决方案3】:

    试试这个

    <script>
     function(){
       $('#row_dim').hide();
       $('#with_codes').change(function() {
          if($('#with_codes').val() == true)
          {
            $('#row_dim').show();
          } 
          else
          {
            $('#row_dim').hide();
          }
       });
     }()
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-09
      • 2018-02-27
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 2023-03-26
      相关资源
      最近更新 更多