我想通过单击复选框的标签来提交表单。复选框未显示,标签样式为按钮。这是我的代码:
<%= 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();
}
});
但是这样做,样式化的标签动画不起作用。解决此问题的方法是什么?先谢谢了。
最佳答案
在这里您在条件中设置值而不是引用它的值。
$('#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/