【问题标题】:How to send data by clicking on a label for a checkbox如何通过单击复选框的标签来发送数据
【发布时间】:2017-03-27 17:25:25
【问题描述】:

我想通过单击复选框的标签来提交表单。复选框未显示,标签样式为按钮。这是我的代码:

<%= form_tag(fetch_games_index_path, method: :get, id: 'games-filter-form', remote: true) do %>
  <%= check_box_tag 'mobile[]', 'true', false, id: 'games-filter-checkbox', class: 'games-filter-checkbox' %>
  <label for="games-filter-checkbox" id="game-mobile-0"></label>
<% end %>

以及对应的js:

$('#game-mobile-0').click(function () {
    $('#games-filter-form input[type="hidden"]').submit();
});

通过这样做,当我第一次单击标签时,它将复选框设置为true,但发送的参数为空。当我再次单击标签时,复选框设置为false,我可以在参数中看到:"mobile"=&gt;["true"]。我尝试了以下代码:

$('#game-mobile-0').click(function () {
  if($('#games-filter-checkbox').prop('checked', true)) {
    $('#games-filter-form input[type="hidden"]').submit();
  }
});

但是这样做,带有样式的标签的动画不起作用。解决此问题的方法是什么?先谢谢了。

【问题讨论】:

    标签: jquery html css ruby-on-rails


    【解决方案1】:

    在这里你设置条件中的值而不是引用它的值。

    $('#game-mobile-0').click(function () {
      if($('#games-filter-checkbox').prop('checked', true)) {
        $('#games-filter-form input[type="hidden"]').submit();
      }
    });
    

    http://api.jquery.com/prop/#prop-propertyName-value

    $('#game-mobile-0').click(function () {
       // cache a reference
       var checkitem = $('#games-filter-checkbox');
       // set to the value it is NOT at present (check if not, un-check if checked)
       checkitem.prop('checked', !checkitem[0].checked)
       // if checked now, submit
       if(checkitem[0].checked) {
           // submit form with this id:
           $('#games-filter-form').submit();
       }
    });
    

    【讨论】:

    • 不过,问题仍然存在。它提交表单并且不会为我的样式标签设置动画。
    • 什么是动画?提交表单后,您想将标签样式更改为其他样式吗?
    • 标签样式与提交表单没有任何关系。如果您想在提交发生时更改样式,您应该使用 jquery addclass 或 css 方法,例如.$('#game-mobile-0').removeClass( "oldClass").addClass( "newClass" );$('#games-filter-form').submit(); 之后
    • 刚刚添加了一个按钮的截图
    • 样式可能是一个不同的问题和不同的问题 - 即如何在复选框上设置图像样式?或者一些这样的问题,样式与表单的提交无关。请注意,某些浏览器不会在表单上提交隐藏字段 - 您可以在其他地方搜索该问题。
    【解决方案2】:

    这段代码有帮助:

    $('#game-mobile-0').click(function () {
      setTimeout(function () {
        $('#games-filter-form input[type="hidden"]').submit();
      }, 300);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-12
      • 2021-05-25
      • 1970-01-01
      • 2013-12-04
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多