javascript - Laravel product filter with checkboxes
I have modelProduct
, and I have scope Filter:
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;
}
And I have frontend checkboxes with name attributes:
@foreach($category->attribute as $attribute)
<section >
<h3 >
{{ $attribute->getTranslatedAttribute('title') }}
<span onclick="$('#filter-{{ $attribute->id }}').slideToggle();">
<i ></i>
</span>
</h3>
<div id="#filter-{{ $attribute->id }}">
<form id="from-{{ $attribute->id }}" action="" method="GET">
<div >
@foreach($attribute->attributeValue as $value)
<div >
<div >
<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 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
Filters working, but my Javascript code working badly. When I click on checkbox, and later want uncheck him, it doesn't work. And multiple click checkbox also not working, In get param I get duplicate attributes. How I can fix this?
Answer
Solution:
You should use php code outside the JS function. And below is the code, you can try this.
Try above code.