我有一个输入复选框作为类别过滤器。我只想存储在var checkedAttr
中检查的数组中的输入复选框的值。然后做一个测试,如果任何已经存在的值匹配数组中的任何值,并且它是否删除它。我遇到的问题是...当单击一个输入复选框时,将存储该循环的次数为$each
循环的次数或输入复选框,在这种情况下(三次)。我还注意到,如果取消选中多个选项,然后重新检查同一个选项,则会循环添加值的次数为$each
,并以某种方式绕过数组中的删除操作。我只想在每次用户选中或取消选中时从数组中添加(检查值)/删除(未检查的值)。如何保存输入复选框值的存储数组?
这是jsfiddle。
HTML:
<div id="category-list">
<h1>Categories</h1>
<input class="categories" type="checkbox" name="filter" value="Math" checked>Math<br/>
<input class="categories" type="checkbox" name="filter" value="Science" checked>Science<br/>
<input class="categories" type="checkbox" name="filter" value="Reading" checked>Reading
</div>
的jQuery:
var checkedAttr = []; // array for checked attributes
// change event listener for whenever one or more of the following checkboxes have been checked/unchecked
$('#category-list :checkbox').change(function()
{
var value = $(this).val();
if($(this).is(':checked')) // checked
{
console.log(value + ' is now checked!!!!!!!!!!!!!!!!!!!!!!!!');
$('#category-list :checkbox').each(function(i, item){ // loop thru the input checkboxes
if(!(value === $(item).val())) // check if the current value does NOT match that already stored in array
{
checkedAttr.push(value); // add value to array
console.log("checkedAttr:", checkedAttr);
}
else // if it does match...
{
checkedAttr.splice(i, 1);// remove it from array
console.log("checkedAttr:", checkedAttr);
}
});
// check which attributes are checked and store in 'checkedAttr' array
//$('input[name=filter]').each(function(i, item){
//});
}
else // unchecked
{
console.log(value + ' is now unchecked!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
完美的作品!谢谢!每当复选框更改时,循环的冗余度为 – TheAmazingKnight
。只需在开头创建一个,然后继续进行验证 –