Reputation: 18680
I have the following HTML select:
<select class="form-control" id="band_id" name="band_id">
<option selected="selected" value="">Choose a band...</option>
<option value="66">Adolfo Little</option>
<option value="96">Aisha Bosco</option>
<option value="90">Alize Glover</option>
</select>
I need to build a filter where the condition is the #band_id
selected so I made this jQuery code:
$("select#band_id").change(function (ev) {
ev.preventDefault();
var band_id = $('select#band_id');
if (band_id.val() != undefined) {
band_id.attr('selected', 'selected');
}
location.href = '/albums/bands/' + band_id.val();
});
Because the location.href
the page gets reloaded and the URL changes so the SELECT is reset and I "loose" the selected value.
I can think in two ways to fix this:
I don't know is there any other way to achieve this. Do you have any other idea? (if it's with an example better)
Upvotes: 0
Views: 272
Reputation: 62666
You can use localStorage for that:
if (localStorage.getItem("band_id")) {
$("select#band_id").val(localStorage.getItem("band_id"))
}
$("select#band_id").change(function (ev) {
ev.preventDefault();
if ($(this).val() != undefined) {
$(this).attr('selected', 'selected');
localStorage.setItem("band_id", $(this).val());
}
location.href = '/albums/bands/' + $(this).val();
});
If we have the value saved - set the value of the select
element to that values.
Once we change the value in the select
element - save the new value in the localStorage.
Note that I removed the usage of the
band_id
from this example as it's not needed. You havethis
you can use inside thechange
function.I'm also not sure why you change the
selected
attribute - you redirect the user immediately to a new page (this change will have no effect at all).
Upvotes: 1