当复选框被选中时,将其值存入数组中

4
我正在使用jQuery编程,以下是我的代码:

我正在使用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到“SelectedCategoryIDs”中。同样,当我取消已选中的母类别时,它将从“SelectedCategoryIDs”中删除所有与所有子类别相对应的ID。
所以,你能帮我实现这个吗?
我希望我解释得清楚,如果有任何问题,请告诉我。

你能展示一下你的HTML吗? - blurfus
完成了,看看我的更新的问题。 - Venelin
3个回答

2
只需创建一个数组,然后用逗号分隔符连接它:
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

我只是在原始代码中添加了几行。OP正在监听复选框的onclick事件,但更好的选择是onchange,但没有人提到这一点... - Marcos Pérez Gude
点击已经被点击的项目应该取消选择它;原帖作者已经在他们的代码中考虑到了这一点。 - randomusername
你的解决方案可能更好,但这段代码易于操作,他可以改进它。 - Marcos Pérez Gude

0

这里是你想要实现的示例。我使用了underscore.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);
 });
})

这是更新后的代码,不使用 underscore 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);
 });
})

0
在你的 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(',');
  });
});


SelectedCategoryIDs未定义。 - Venelin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接