简体   繁体   中英

javascript - select option jquery issue

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.

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 .)

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> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM