【问题标题】:jQuery: Looping through checkbox and storing in an array?jQuery:遍历复选框并存储在数组中?
【发布时间】:2015-08-06 10:52:16
【问题描述】:

我有一个带有复选框的页面,我试图在单击按钮时循环它们,检查是否选中了其中任何一个,如果没有选中,我想显示警报。这就是我所拥有的,但它不起作用。

$(document).ready(function() { 
    $('input#addnewwebsite').click(function() {
        $('input[type=checkbox]').each(function() {
            var categories = [];
            var $(this) = $(this);    
            if ($(this).is(':checked') == true) {
                categories.push($(this)); // checked, add to array
                break;
            }
            if (categories != null) {
                alert('You must select at least one category.');
                return false;
            }
        });
    });
});

【问题讨论】:

  • var $(this) = $(this); .. 你确定这行得通吗?

标签: jquery arrays checkbox


【解决方案1】:

您可以简单地使用带有长度的:checked 选择器。

$('input#addnewwebsite').click(function() {
    var categories = $('input:checkbox:checked');
    if(!categories.length){
       alert('You must select at least one category.');  
    }
})

为什么你的代码不起作用。

  • 您正在为每个复选框迭代初始化 var categories = [];

【讨论】:

    【解决方案2】:
    var categories = [];
    $(document).ready(function() { 
        $('input#addnewwebsite').click(function() {
            $('input[type=checkbox]').each(function() {
    
                var $this = $(this);    
                if ( $this.is(':checked') == true) {
                    categories.push( $this ); // checked, add to array
                    break;
                }
    
                if (categories.length == 0 ) {
                    alert('You must select at least one category.');
                    return false;
                }
            });
        });
    });
    

    在您的代码中,类别数组需要在循环之外,因为它正在为每个复选框迭代重新初始化。 此外,您需要检查数组的长度,而不是检查 categories != null,如果它的 ZERO 则提醒消息。 你已经分配了 var $(this) = $(this) 这没有任何意义。相反,它应该是 var $this = $(this) 或者变量名可以是任何东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-06
      • 2013-09-28
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多