【问题标题】:Checkbox values fetching using Jquery使用 Jquery 获取复选框值
【发布时间】:2018-08-25 21:34:33
【问题描述】:

我有多个复选框。用户可以选择一个或多个。所以,我必须得到这些复选框的值。

 <div class="filters col-md-12">
                        <div class="form-group">
                            @foreach($destination as $dest)
                            <label class="radio-inline" id="desti">{{$dest->destination}}
                                <input  type="checkbox" name="dest_val" value="{{$dest->id}}">
                                <span class="checkmark"></span>
                            </label>
                            @endforeach
                        </div>
                    </div>

顺便说一句,我使用的是 Laravel。所以,在 Jquery 中,我正在写这个:

   $(document).on('click','#desti',function () {

           var destination = $("input[name='dest_val']:checked").val()
               console.log(destination);


       });

但是,它没有给我正确的值。当我点击第一个复选框时,它给出的值 = 1,这是正确的,当我点击 2 时,它给出的 2 是正确的。因此,当检查 1 并检查 2 时,我将两个 1 添加到前一个 1 中,这使得 1(3)/ 1 乘以 3,我也得到 1 两个。所以,我想要的是当我检查 2 时,我只得到 2 而不再是。

反之亦然。有人可以帮忙吗?

【问题讨论】:

    标签: jquery checkbox


    【解决方案1】:

    你不能在 DOM 元素上重用 id 属性而不得到像这样奇怪的结果。尝试为每个复选框或类名使用唯一的 id。

    您还需要为复选框指定一个唯一的名称。

    下面是一个使用类名的例子:

    HTML

    <div class="filters col-md-12">
        <div class="form-group">
            @foreach($destination as $dest)
                <label class="radio-inline checkbox-label">{{$dest->destination}}
                    <input type="checkbox" value="{{$dest->id}}">
                    <span class="checkmark"></span>
                </label>
           @endforeach
        </div>
    </div>
    

    JS

    $(document).on('click','.checkbox-label',function () {
        var destination = $(this).find('input[type="checkbox"]').val();
        console.log(destination);
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-20
      • 2012-07-02
      • 2010-11-20
      • 2012-06-07
      • 2013-09-01
      • 2021-12-15
      • 1970-01-01
      • 2013-01-11
      • 2011-02-19
      相关资源
      最近更新 更多