jquery - 如何通过单击复选框的标签来发送数据

标签 jquery html css ruby-on-rails

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

<%= 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"=>["true"]。我尝试了以下代码:

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

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

animated_button

最佳答案

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

$('#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 - 如何通过单击复选框的标签来发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43052793/

相关文章:

javascript - 在事件更改时更新变量 jquery

jquery - CSS伪类覆盖类

javascript - 调整浏览器大小时,如何将 img 标签居中放入 div 标签?

Javascript/JQuery 如何验证电话号码

javascript - 将 jquery-ui datepicker 与 require.js 一起使用

html - 中间有单词的水平线的CSS技巧

html - 调整浏览器大小时如何阻止单页站点自动滚动?

html - 删除 Div 元素之间的间隙

php - 鞋子/衬衫尺寸可点击列表而不是下拉菜单

javascript - 将 simpleCart 项目添加到表单作为输入值