treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Javascript - Remember what was selected after refresh

  • Hi all,

    I have a simple drop down that allows you to choose a country. On my site if the address in the form comes out wrong it refreshes the page and brings up a validation box. If someone choses Canada it defaults back to the US when the page refreshes. With javascript could it remember Canada after the refresh?

    <td>
    <select name="scoShipCountry">
    <option value="US">United States</option>
    <option value="CA">Canada</option>
    </select>
    </td>
  • You could simply store some cookies, you could do javascript to accomplish this. Can't really give you much more than that as I'm not proficient enough in JS, but 'cookies' are what you're looking for.
  • Great! I'll give this a try.
  • Yep, as JavaScript is client-side, the only thing you'll be able to do is set cookies. It's nice and easy, just set the cookie when they choose Canada and then read it on page load
  • Or, you could just set the location hash:

    HTML
    <select id="country" name="scoShipCountry">
    <option value="US">United States</option>
    <option value="CA">Canada</option>
    </select>
    JS
    document.getElementById('country').addEventListener('change', function(){
    window.location.hash = this.value;
    }, false);