javascript - select option jquery issue -


in application, want let user select option drop down menu @ anytime. when page reloads, goes default value (the first element in drop down list).

my html looks this:

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

in javascript, use following letting user select option:

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

i retrieving value of author selected before page reloads localstorage by:

auid = localstorage.getitem("latestauthor"); 

can tell me how fit example code snippet let me select option drop down menu, , same option stays selected when page reloads, user can select option drop down menu @ anytime well.

on page load, once select box exists, , once you've retrieved auid local storage, this:

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

the if there because if you've never set value in local storage, that's you'll getitem.


side note: when getting value, don't use prop('value'). use .val:

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

complete example on jsfiddle (since stack snippets don't allow local storage ☹ ). assumes it's in script tag @ end of html, before closing </body> tag (which should put them unless have reason not to).

// scoping function 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 reason can't put script tag @ end, 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 result of $("#tabs .author") in variable if want avoid doing twice, doing twice on page load nothing.)


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -