选中时将复选框的值获取到数组中

Getting a value of checkbox into array when checked

提问人:Venelin 提问时间:12/18/2015 最后编辑:fionaredmondVenelin 更新时间:12/18/2015 访问量:1839

问:

我正在使用 jQuery,这是我到目前为止的代码:

$('.CategoryInput').each(function() {
    $(this).click(function() {
        var CategoryID  = $( this ).attr( "category" );
        var Clicked     = $( this ).attr( "clicked" );
        if(Clicked == 0){
            $("#Category" + CategoryID).css({backgroundColor: '#fc3b66'});
            $("#Category" + CategoryID).find( ".state" ).css({color: '#fff'});
            $(".subcat" + CategoryID).css({backgroundColor: '#fc3b66'});
            $(".subcat" + CategoryID).find( ".state" ).css({color: '#fff'});
            $(".SubCategoryInput" + CategoryID).prop('checked', true);
            $(".SubCategoryInput" + CategoryID).attr('clicked','1');
            $(this).attr('clicked','1');
        } else {                    
            $("#Category" + CategoryID).css({backgroundColor: '#fdfdfd'});
            $("#Category" + CategoryID).find( ".state" ).css({color: '#6a6d76'});
            $(".subcat" + CategoryID).css({backgroundColor: '#fdfdfd'});
            $(".subcat" + CategoryID).find( ".state" ).css({color: '#6a6d76'});
            $(".SubCategoryInput" + CategoryID).prop('checked', false);
            $(".SubCategoryInput" + CategoryID).attr('clicked','0');
            $(this).attr('clicked','0');
        }

        });

});

这是我的HTML:

 <div class="container">                 
    <h1>Selecciona los productos que elaboras:</h1>
    <?PHP
    $r = mysql_query("SELECT * FROM `Category` WHERE `subCategory`='0' ORDER by Position ASC");
        while($rowi = mysql_fetch_array($r))
                {
                $id = $rowi['id'];
                $Name = $rowi['Name'];
                $Description = $rowi['Description'];

    ?>
    <div class="row">
        <div class="maintag" id="Category<?PHP echo $id;?>">
            <label class="state" for="categories"><?PHP echo $Name;?></label>
            <input type="checkbox" class="CategoryInput" name="categories" category="<?PHP echo $id;?>" clicked="0">          
            (<?PHP echo $Description;?>)
        </div>
    </div>
    <div class="row">
    <?PHP 
        $r1 = mysql_query("SELECT * FROM `Category` WHERE `subCategory`='$id' ORDER by Position ASC");
            while($rowi1 = mysql_fetch_array($r1))

            {
                $id1 = $rowi1['id'];
                $Name1 = $rowi1['Name'];                                
    ?>

        <div class="col-md-4" style="padding-left:0px;">
            <div id="subtag<?PHP echo $id1;?>" class="subcat<?PHP echo $id;?> supersub">
                <label class="state" for="categories"><?PHP echo $Name1;?></label>
                <input type="checkbox" name="subcategory" class="SubCategoryInput<?PHP echo $id;?>" SubCategory="<?PHP echo $id1;?>" clicked="0">          
            </div>
        </div>  

                <?PHP } ?>
        </div>      
<?PHP } ?>
</div>                          

我有几个复选框,我用作类别。这些类别具有子类别,因此此代码只是突出显示选中的复选框。如果所选复选框来自母类别,则会突出显示所有子类别的所有复选框。同时将它们设置为 .checked

到目前为止,我所取得的一切成就都是我想要的。现在,我被困在如何获取所选复选框的id并将其添加到如下所示的变量中:

var SelectedCategoryIDs = '12,435,123,124,56,34,23';

因此,当我单击母亲类别时,它将添加到所有子类别的 ID 中。此外,当我取消选中已经选中的母类别时,它将删除与所有子类别相对应的所有 ID。SelectedCategoryIDsSelectedCategoryIDs

那么你能帮我实现这个目标吗?

我希望我解释得很好,如果您有任何问题,请告诉我。

JavaScript jQuery 复选框

评论

0赞 blurfus 12/18/2015
你能给我们看看你的HTML吗?
0赞 Venelin 12/18/2015
完成后,请查看我更新的问题。

答:

2赞 Marcos Pérez Gude 12/18/2015 #1

只需制作一个数组,然后用逗号分隔连接它:

var selectedArray = [];
$('.CategoryInput').each(function() {
    $(this).click(function() {
      selectedArray.push($(this).attr('id'));
    });
});

/* and then join: */

var selectedString = selectedArray.join(","); // you'll give all ids comma separated

评论

0赞 Marcos Pérez Gude 12/18/2015
我只将这些行添加到 OP 的原始代码中。 OP 在更好的 onchange 时正在监听 onclick 事件到复选框,但没有人对此说什么......
0赞 randomusername 12/18/2015
单击已单击的项目意味着取消单击它;OP 已经在他们的代码中说明了这一点
0赞 Marcos Pérez Gude 12/18/2015
你的解决方案可能更好,但这段代码很容易操作,他可以改进它
0赞 randomusername 12/18/2015 #2

在回调结束时,只需添加click

var SelectedCategoryIDs = '';

$('.CategoryInput').each(function() {
  $(this).click(function() {
    // Include the old code here...
    
    // Here's the new part
    SelectedCategoryIDs =
      $('.CategoryInput[clicked=1]')
      .map(function() {
        return this.category;
      })
      .get()
      .join(',');
  });
});

评论

0赞 Venelin 12/18/2015
未定义 SelectedCategoryIDs
0赞 Gjohn 12/18/2015 #3

下面是您要实现的目标的示例。我使用了下划线.js和jquery,因为我喜欢它提供的实用方法。

基本上,我的事件处理程序如下所示。_.without 函数基本上将返回没有未选中值的数组。

$(document).ready(function(){
var arr = [];
$("input:checkbox").on("click", function(){
    if ($(this).is(":checked")){
    arr.push($(this).val());
  }
  else {
    arr = _.without(arr, $(this).val());
  }
  $("#arr").text(arr);
 });
})

这是不带下划线 js 的更新代码

https://jsfiddle.net/hrt7cxvp/26/

$(document).ready(function(){
var selectedArray = [];
$("input:checkbox").on("click", function(){
    if ($(this).is(":checked")){
    selectedArray.push($(this).val());
  }
  else {
    selectedArray.splice(selectedArray.indexOf($(this).val()));
  }
  $("#arr").text(selectedArray);
 });
})