Javascript 收集复选框的值,并使用所述值自动选中其他div中的复选框

Javascript 收集复选框的值,并使用所述值自动选中其他div中的复选框,javascript,jquery,html,css,ruby-on-rails,Javascript,Jquery,Html,Css,Ruby On Rails,复选框似乎没有值,所以应该将值存储在html数据属性中。 此外,还必须使用jQuery包装这个 html 首先,您需要知道如何识别范围内的每个复选框。当您使用id将值作为参数传递时,一种简单的方法是使用class属性,如下所示: $(':checked.platbtn').map(function(){ return $(this).data('value');}).get(); <%= check_box_tag "game[platforms][id][]", platform.id

复选框似乎没有
,所以应该将值存储在html数据属性中。 此外,还必须使用jQuery包装
这个

html


首先,您需要知道如何识别范围内的每个复选框。当您使用id将值作为参数传递时,一种简单的方法是使用class属性,如下所示:

$(':checked.platbtn').map(function(){ return $(this).data('value');}).get();
<%= check_box_tag "game[platforms][id][]", platform.id, false, class: platform.id  %>

我在这里尝试了许多jQuery代码片段。我对jquery这个东西很陌生,所以我肯定我可能在某个地方搞砸了:)给我们一个可能有助于回答的答案。我刚刚添加了一个。这只会从上述复选框中获取值,其他什么都不会。更进一步,我注意到它会从我的所有结果中检查与id匹配的所有框。有没有办法把范围缩小到一个结果
您可以查看JQuery
.first()
方法。谢谢!成功了最后一件事:切换怎么样?现在,如果我按下按钮,复选框将保持选中状态,反之亦然。您可以添加验证:
if($(this).is(“:checked”)
。如果这是
false
,那么您只需
prop('checked','')
。此外,如果你也能投票支持我的答案,我将非常高兴
<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>
var values = $('input:checkbox:checked.platbtn').map(function() {
return this.value;
}).get();
<input type="checkbox" name="options" class="platbtn" data-value= <%=platform.id %> >
$(':checked.platbtn').map(function(){ return $(this).data('value');}).get();
<%= check_box_tag "game[platforms][id][]", platform.id, false, class: platform.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
});