简体   繁体   中英

Change selected option

I have the following select:

        <select id="sitestyle" name="stil">
            <option value="blue">Blå</option>
            <option value="green">Grön</option>
            <option value="red">Röd</option>
            <option value="pink">Rosa</option>                
        </select>

I'm saving the value the user has selected to localStorage . Say the user selects value="pink" and it is then saved to the localStorage , user closes browser and opens again i want value="pink" to be selected automatically. Currently it is always value="blue" regardless of what is saved in the localStorage .

Can't use jQuery/Ajax but javascript is fine.

edit

I have the following JS:

function setStyleFromStorage(){
    style = localStorage.getItem("style");
    document.getElementById('css_style').setAttribute('href', style);
    if(style == "blue"){
        document.getElementById("sitestyle").selectedIndex() = 0;
    }else if(style == "green"){
        document.getElementById("sitestyle").selectedIndex() = 1;
    }else if(style == "red"){
        document.getElementById("sitestyle").selectedIndex() = 2;
    }else if(style == "pink"){
        document.getElementById("sitestyle").selectedIndex() = 3;
    }
}

Use following code to change select box value.

function setStyleFromStorage(){
    if(localStorage.style){
        document.getElementById("sitestyle").value = localStorage.style;
    }
}
document.getElementById("sitestyle").onchange = function(){
     localStorage.style = this.value;  
}

JSFIDDLE

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