我有一個輸入複選框作爲類別過濾器。我只想存儲在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
。只需在開頭創建一個,然後繼續進行驗證 –