I have a problem. I have select with name category and have code:
if (localStorage.getItem('category') !== null) {
$('select[name=category]').val(localStorage.getItem('category')).trigger('change');
$('.form-search').submit();
}
If in Local storage I have id, then I change selected value in select. But How I can submit this form? My code is not working, because page reloading many times..
MY form:
<form method="get" class="form-search">
....
<select name="category">
<option value="1">Auto</option>
<option value="2">Sport</option>
...
</select>
</form>
Because the form hasn't action
, browser submit form to this page and page reloaded and because you don't removed localStorage
the code runned again. So you should remove localStorage category
before submitting form.
var category = localStorage.getItem('category');
if (category !== null) {
$('select[name=category]').val(category).trigger('change');
localStorage.removeItem('category');
$('.form-search').submit();
}
You may not need the trigger
if(localStorage.getItem('category') !== null) { $('select[name=category]').val(localStorage.getItem('category')); $('.form-search').submit(function(e){ e.preventDefault(); }); }
Check code here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.