ReynierPM
ReynierPM

Reputation: 18680

How do I keep the option selected when it changes and I need to reload the page?

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

Answers (1)

Dekel
Dekel

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 have this you can use inside the change 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

Related Questions