2

In my application, I want to let user select an option from the drop down menu at anytime. But when the page reloads, it goes back to the default value (the first element in the drop down list).

My HTML looks like this:

<select class="author">
    <option value="aaa">aaa</option>
    <option value="bbb">bbb</option>
    <option value="ccc">ccc</option>
</select>

In my javascript, i use the following for letting the user select an option:

auid = $('#tabs' .author option:selected').prop('value');

I am actually retrieving the value of author that was selected before page reloads from the localstorage by:

auid = localStorage.getItem("latestAuthor");

Can someone tell me how does this all fit together with example code snippet to let me select an option from drop down menu, and the same option stays selected when the page reloads, but the user can select another option from the drop down menu at anytime as well.

1
  • var auid = $('#tabs .author option:selected').prop('value'); with this limited html is the same value asvar auid = $('.author').val(); Commented Feb 6, 2016 at 15:20

2 Answers 2

2

On page load, once that select box exists, and once you've retrieved auid from local storage, do this:

if (auid !== null) {
    $("#tabs .author").val(auid);
}

The if is there because if you've never set the value in local storage, that's what you'll get back from getItem.


Side note: When getting the value, don't use prop('value'). Use .val:

auid = $("#tabs .author").val();

Complete example on jsFiddle (since Stack Snippets don't allow local storage ☹ ). This assumes it's in a script tag at the end of the HTML, just before the closing </body> tag (which is where you should put them unless you have a good reason not to).

// Scoping function to avoid global vars
(function() {
    var auid = localStorage.getItem("latestAuthor");
    if (auid !== null) {
        $("#tabs .author").val(auid);
    }
    $("#tabs .author").on("change", function() {
        auid = $(this).val();
        localStorage.setItem("latestAuthor", auid);
    });
})();

If for some reason you can't put the script tag at the very end, you can use jQuery's "DOM ready" callback:

jQuery(function() {
    var auid = localStorage.getItem("latestAuthor");
    if (auid !== null) {
        $("#tabs .author").val(auid);
    }
    $("#tabs .author").on("change", function() {
        auid = $(this).val();
        localStorage.setItem("latestAuthor", auid);
    });
});

(You can cache the result of $("#tabs .author") in a variable if you want to avoid doing it twice, but doing it twice on page load is nothing.)

Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the snippet...it is able to retrieve the previous value and selects it from the drop down menu, but i cannot change the value (to a new option) from the drop down menu...even after clicking on some other option, it stays on the same option...!
@Vasa: Not with the code above. That problem doesn't happen (try the fiddle to see). You must be doing the call setting the value at the wrong time. Take a close look at when I'm doing that in the above code.
just to mention, my actual statement is something like this: $('#tabs' + rId + ' .pool .author') but for the sake of question i simplified it...if that changes anything?
@Vasa: Not really, no.
unless the value of rdl appended to tabs makes it an invalid id for the tab like '#tabsidonotexist .pool .author' - and of course you must do that in both places in the code
1

Works fine for me.

Possible typo error

auid = $('#tabs' .author option:selected').prop('value');
               ^

Sample:

$(".btn").on("click", function() {
  var auid = $('#tabs .author option:selected').prop('value');
  console.log(auid);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
  <select class="author">
    <option value="aaa">aaa</option>
    <option value="bbb">bbb</option>
    <option value="ccc">ccc</option>
  </select>
</div>
<button class="btn">Click Me</button>

Also for sample of integrating with LocalStorage, check following code:

Note: Stackoverflow does not allows to access localStorage and you should test it on fiddle.

JSFiddle

var _lsKey = "test";
function registerEvents(){
	$(".btn").on("click", function() {
    var auid = $('#tabs .author option:selected').prop('value');
    saveValueToLS(_lsKey, auid);
	});
}

function saveValueToLS(key, value){
	localStorage.setItem(key, value);
}

function getValueFromLS(key){
	return localStorage.getItem(key);
}

function initializeSelect(){
	var lsVal = getValueFromLS(_lsKey);
  $(".author").val(lsVal);
}

function initializePage(){
	registerEvents();
  initializeSelect();
}
initializePage();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="tabs">
  <select class="author">
    <option value="aaa">aaa</option>
    <option value="bbb">bbb</option>
    <option value="ccc">ccc</option>
  </select>
</div>
<button class="btn">Click Me</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.