带有复选框值的Jquery过滤器数组并输出新数组

时间:2011-08-16 15:08:36

标签: jquery arrays checkbox

我有一个数组:

var arrayList = [{"color":"red","size":small"},{"color":"brown","size":medium"},{"color":"red","size":large"}];
带复选框的

<input name="red" type="checkbox" value="red" />
<input name="brown" type="checkbox" value="brown" />
<input name="small" type="checkbox" value="small" />
<input name="large" type="checkbox" value="large" />

我需要能够使用复选框值过滤数组以输出新数组。

如果我选中'red',新数组应为:

var arrayList = [{"color":"red","size":small"},{"color":"red","size":large"}];

如果我检查'红色'和'大'我会得到:

var arrayList = [{"color":"red","size":large"}];

感谢您提供任何帮助。

我需要澄清我的问题,这是我的过滤器代码:

//this is the top level array generated with all products
    var product = [{"price":"200","color":"red","size":small"},{"price":"250","color":"brown","size":medium"},{"price":"300","color":"red","size":large"}];

// displayed products array
    var filterdProducts = [];  
            var key = 0;

        //start of price range filter
            if(!minPrice && !maxPrice){
                filterdProducts = products;
            } else{
                $.each(products, function(i, object) {   
                    var curentPrice = parseFloat(object.price); 
                    var priceMinOk = true;
                    var priceMaxOk = true;
                    // filter results match the price range
                    if(maxPrice || minPrice){
                        if(maxPrice && maxPrice<curentPrice){
                            priceMaxOk = false;
                        }
                        if(minPrice && minPrice>curentPrice){
                            priceMinOk = false;
                        }
                    }  
                    //  loop over list and get only related to new array
                     if( priceMinOk && priceMaxOk ){  
                        filterdProducts[key] = object;                  
                        key++;

                     }  

                });
            } 

我需要为该过滤器添加复选框功能,以便我也可以按大小和颜色进行过滤。希望这有帮助

1 个答案:

答案 0 :(得分:0)

试试这个

var arrayList = [{"color":"red","size":"small"},{"color":"brown","size":"medium"},{"color":"red","size":"large"}];
var newArrayList = [];


   if($("input[value=red]").checked){
       if($("input[value=large]").checked){
         newArrayList.push({"color":"red","size":"large"});
       }
       else{
          newArrayList.push({"color":"red","size":"small"}).push({"color":"red","size":"large"});
       }

   }