How do you Save a Selected Option in a Selection List
16,249
To save on change:
<script>
document.addEventListener('DOMContentLoaded', function () {
var input = document.getElementById('job');
if (localStorage['job']) { // if job is set
input.value = localStorage['job']; // set the value
}
input.onchange = function () {
localStorage['job'] = this.value; // change localStorage on change
}
});
</script>
For individual methods:
var input = document.getElementById('job');
function loadSettings() {
if (localStorage['job']) {
input.value = localStorage['job'];
}
}
function saveSettings() {
localStorage['job'] = input.value;
}
Author by
Admin
Updated on August 20, 2022Comments
-
Admin over 1 year
For my web app I have a selection list coded as below;
<select name = 'job' id = 'job'> <option value = 'jobselect'>Select Profession</option> <option value = 'job1'>Mechanical Engineer</option> <option value = 'job2'>Software Engineer</option> <option value = 'jobother'>Other</option> </select>
in the settings page. this page is linked to a 'save.js' file where the user input is supposed to be saved. i am using HTML and JavaScript - and no knowledge of PHP. In my JS file i have two functions - saveSettings and loadSettings. i'm stuck as to how to save it to localStorage (JavaScript) in the saveSettings function and reading it back to the user in the loadSettings. Any help would be much appreciated thanks x
-
Admin over 11 yearsok thanks. i should have mentioned this sorry but i have two functions in my JS file called saveSettings and loadSettings. is it possible to split this up between the two functions?
-
Admin over 11 yearsok thanks. i have two functions in my save.js file would it be possible for you to help me split the code between the two? like the first line of codde you gave me would probably go into saveSettings function i have, but what would i do about the second one, loadSettings? like what would i code to make sure the selected value stays selected and doesn't revert back to the default? thanks again
-
trumank over 11 years@MeganSime ok - I've split it.
-
Admin over 11 yearsthanks a lot for the help but it broke my settings button so i can't access the page - i don't mean to offend you but are you sure you've got the write code?
-
Admin over 11 yearsor could you please tell me how to attach the first block of code you gave me to a line of code like; $('#settings').bind('pageAnimationStart', loadSettings); that might work better