【问题标题】:How to create an array in jquery when checkbox is clicked?单击复选框时如何在jquery中创建数组?
【发布时间】:2016-02-26 14:03:13
【问题描述】:

我有一个品牌复选框和一个价格复选框。现在,如果用户单击复选框,我想要一组品牌 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 来实现这一点。请帮忙

【问题讨论】:

  • 复选框可以触发onclick事件,只需添加onclick="myfunction()",然后在该函数中执行您需要执行的操作。

标签: javascript php jquery arrays checkbox


【解决方案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]));
});

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2018-05-17
    相关资源
    最近更新 更多