我有模型Product
,并且有范围筛选器:
public function scopeFilter($query)
{
if (request('min') && request('max')) {
$query->where('price', '<=', request('max'))->where('price', '>=', request('min'));
}
if (request('attr')) {
$query->whereHas('attribute', function ($q) {
$q->whereIn('attribute_value_id', explode(',', request('attr')));
});
}
return $query;
}
我有带有名称属性的前端复选框:
@foreach($category->attribute as $attribute)
<section class="widget">
<h3 class="widget-title">
{{ $attribute->getTranslatedAttribute('title') }}
<span class="float-right ico-down" onclick="$('#filter-{{ $attribute->id }}').slideToggle();">
<i class="icon-chevron-down"></i>
</span>
</h3>
<div id="#filter-{{ $attribute->id }}">
<form id="from-{{ $attribute->id }}" action="" method="GET">
<div class="row">
@foreach($attribute->attributeValue as $value)
<div class="col-md-6">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
type="checkbox"
id="filter-{{ $value->id }}"
name="attr"
value="{{ $value->id }}"
onclick="this.checked ? checkFunc() : removeFunc()"
@if(request('attr') && in_array($value->id, explode(',', request('attr')))) checked @endif>
<label class="custom-control-label" for="filter-{{ $value->id }}">{{ $value->getTranslatedAttribute('value') }}</label>
</div>
</div>
@endforeach
</div>
</form>
</div>
</section>
@endforeach
@section('js')
<script>
var url = '?attr=';
function checkFunc() {
var id = $("[name=attr]:checked").map(function () {
return this.value;
}).get().join(",");
@if(request('attr'))
window.location.href = url + "{{ request('attr') }}," + id;
@else
window.location.href = url + id;
@endif
};
</script>
@endsection
过滤器正常运行,但是我的Javascript代码无法正常运行。当我单击复选框,以后又想取消选中他时,它不起作用。并且多次单击复选框也不起作用,在获取参数中,我得到重复的属性。我该如何解决?
答案 0 :(得分:-2)
您应该在JS函数之外使用php代码。下面是代码,您可以尝试一下。
<script>
<?php
$attr = "";
if(request('attr')) {
$attr = request('attr');
}
?>
var url = '?attr='+<?php echo $attr; ?>;
function checkFunc() {
var id = $("[name=attr]:checked").map(function () {
return this.value;
}).get().join(",");
window.location.href = url + id;
};
</script>
尝试上面的代码。