<% if !result.platforms.nil? %>
<div class="platforms">
<div class="btn-group" data-toggle="buttons">
<% result.platforms.each do |platform| %>
<label class="btn btn-default">
<input type="checkbox" name="options" class="platbtn" value= <%=platform.id %> ><%= platform["name"] %></label>
<% end %>
</div>
</div>
<% end %>
...
<% result.platforms.each do |platform| %>
<span class='select_platform'>
<%= check_box_tag "game[platforms][id][]", platform.id %>
<%= label_tag "game[platforms][name][]", platform.name %>
</span>
<% end %>
这段代码变成...
<span class="select_platform">
<input id="game_platforms_id_" name="game[platforms][id][]" type="checkbox" value="19">
<label for="game_platforms_name_">Game Boy Advance</label>
</span>
好的,有了这个,我想获取我在#platforms div 中按下/选中的按钮/复选框的值(platform_id),并自动选中跨度类“select-platform”中的相应框。
我尝试了多种不同的方法来获取所述框的值,但是当我去查看数组时,里面什么也没有。我不确定在这两种情况下我是否只是简单地以错误的方式询问值,或者是什么。
我尝试获取和存储值的最后一种方法是使用在堆栈溢出的其他地方找到的这段代码片段。
var values = $('input:checkbox:checked.platbtn').map(function() {
return this.value;
}).get();
最佳答案
首先,您需要知道如何识别 span 中的每个复选框。当您使用 id 将值作为参数传递时,一种简单的方法是像这样使用类属性:
<%= check_box_tag "game[platforms][id][]", platform.id, false, class: platform.id %>
这样您就可以使用 $('.your_id')
访问此复选框,因此您可以像这样在所有平台复选框上附加更改事件:
$(".platforms input[type=checkbox]").on("change", function() {
var selected = $(this).val(); // This will get the value
$("."+selected).prop('checked', 'checked'); // This will check the box
});
关于javascript - 收集复选框的值并使用所述值自动选中其他 div 中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22935882/