【问题标题】:Getting a value of checkbox into array when checked选中时将复选框的值放入数组
【发布时间】:2016-03-24 05:26:54
【问题描述】:

我正在使用 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 吗?
  • 完成,查看我更新的问题。

标签: javascript jquery checkbox


【解决方案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

【讨论】:

  • 我只将这些行添加到 OP 的原始代码中。当 onchange 更好时,OP 正在监听 onclick 事件到复选框,但没有人对此一言不发......
  • 点击一个已经被点击的项目意味着取消点击它; OP 已经在他们的代码中说明了这一点
  • 你的解决方案可能更好,但是这段代码很容易OP,他可以改进它
【解决方案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(',');
  });
});

【讨论】:

  • SelectedCategoryIDs 未定义
【解决方案3】:

这是您想要实现的目标的example。我使用 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);
 });
})

这里是没有下划线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);
 });
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    相关资源
    最近更新 更多