如何在单击复选框时在jquery中创建数组?

时间:2016-02-26 14:03:13

标签: javascript php jquery arrays checkbox

我有一个品牌复选框和价格复选框。现在,如果用户点击复选框,我想要一个brand_id数组和一系列价格。

<div class="left-filters__inner--block">
  <ul class="filter-data filter-data-brands" id="brands_list">
    @foreach(App\Brand::all() as $brand)
      <li>
        <label for="{{$brand->name}}" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
           <input type="checkbox" name="brands[]" id="{{$brand->name}}" class="mdl-checkbox__input"  data-value="{{$brand->id}}">
           <span class="mdl-checkbox__label">{{$brand->name}}</span>                       
        </label>
      </li>
    @endforeach
  </ul>
</div>

带复选框的价格视图

<div class="left-filters__inner--block">
    <ul class="filter-data filter-data-price" id="price_list">
        <li>
            <label for="less-20" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
                <input type="checkbox" id="less-20" class="mdl-checkbox__input" name="price" data-value="0,20">
                <span class="mdl-checkbox__label">Less than 20</span>
            </label>
        </li>
        <li>
            <label for="21-50" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
               <input type="checkbox" id="21-50" class="mdl-checkbox__input" name="price" data-value="21,50">
               <span class="mdl-checkbox__label">21  -  50</span>
             </label>
         </li>
         <li>
              <label for="51-100" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
                   <input type="checkbox" id="51-100" class="mdl-checkbox__input"  name="price" data-value="51,100">
                   <span class="mdl-checkbox__label">51  -  100</span>
               </label>
         </li>

现在,当用户点击特定品牌或价格的复选框时,我想要一个看起来像这样的数组。

Array
    (
        [brand_id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

        [price] => Array
        (
            [0] => 0,1000
            [1] => 1000,2000
        )

    )

我想用jquery实现这个目的。请协助

1 个答案:

答案 0 :(得分:1)

https://jsfiddle.net/2moqx8da/

$("input:checkbox").click(function() {
    var brandids=[], prices=[];
    $("input[name='brands']:checked").each(function() {
    brandids.push($(this).val())
  });
  $("input[name='price']:checked").each(function() {
    prices.push($(this).val())
  });
  $('#output').text(JSON.stringify([brandids, prices]));
});