I am making a filter with jQuery and Laravel (PHP). It filters the data when I click the checkbox or radio button but, if I click checkbox or radio button and refresh the page the state of checked checkbox or radio button will no longer remain. I want the checked state to remain even after the page reloads.
This is my code.
<div class="search">
<input type="radio" name="expertise[]" value="backend" />programmer
<input type="radio" name="expertise[]" value="frontend" />programmer
</div>
<div class="avail">
<p>
<input type="checkbox" name="available[]" value="20" />20
</p>
<p>
<input type="checkbox" name="available[]" value="30" />30
</p>
</div>
jQuery
<script>
var expertise = [];
var available = [];
$(document).on('change', 'input[name="expertise[]"], input[name="available[]"]', function(e) {
e.preventDefault();
types = [];
available = [];
if (document.location.href.indexOf('filter') > -1) {
var url = '../developers/filter?type=dev';
} else {
var url = '/developers/filter?type=dev';
}
$('input[name="type[]"]:checked').each(function() {
expertise.push($(this).val());
url = url + '&expertise=' + $(this).val();
});
$('input[name="available[]"]:checked').each(function() {
available.push($(this).val());
url = url + '&available=' + $(this).val();
});
if (document.location.href.indexOf('filter') > -1) {
$.get('../developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
} else {
$.get('developers/filter', {
type: 'dev',
expertise: expertise,
available: available,
}, function(markup) {
$('.dev-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
</script>
Laravel controller
public function search(Request $request)
{
$type = $request->get('expertise');
$availability = $request->get('available');
$url = 'filter';
$users = User::where('type','dev')->where('is_approved', '=', 1);
if (!empty($type)) {
$users = $users->where('expertise','dev');
}
$users->when($availability, function ($query, $availability ) {
return $query->where(function ($whereQuery) use ($availability ) {
foreach ($availability as $item) {
$whereQuery->orWhere('avaibility', 'LIKE', $item);
}
});
});
3
Answers
JS/jQuery: Save into localStorage
PHP/Laravel: Save in session,
and then you can change it when they submit
,
You can also store other things.
U can use local storage for saving the state. Suppose if check box is clicked then store it in local storage and if page reloads make a function to extract data from the local storage and apply it.
You are already pushing things to the URL so when you load the page you can check the url query string for what’s set or not.
Note that the
URLSearchParams
needs to be polyfilled in IEThis can also be achieved via the HTML and Laravel:
This is assuming you have this HTML in a .blade.php file