Drop down menu to remember selection and redirect

2019-02-26 06:56发布

问题:

I am making a landing page with a drop down menu which will redirect users to a new directory.

http://steerbox.com/countryselect/

That part is working and now I need to add code to set a cookie when the country is selected, so that the next time the user visits the landing page they will automatically get redirected to that country's directory without having to select from the drop down menu again.

I have found jquery and javascript which will set the cookie on selection of the drop down, but I can't seem to get the drop down to both set the cookie and still redirect the user. Following is the script that I am currently using for the drop down and redirect:

<Script language="JavaScript">
function goto(form) { var index=form.select.selectedIndex
if (form.select.options[index].value != "0") {
location=form.select.options[index].value;}}
</SCRIPT>
<FORM NAME="form1">
<SELECT NAME="select" ONCHANGE="goto(this.form)" SIZE="1">
<OPTION VALUE="">Select Country
<OPTION VALUE="chile">Chile
<OPTION VALUE="colombia">Colombia
<OPTION VALUE="bolivia">Bolivia
</select>
</FORM>

Thanks! Dean

回答1:

I agree with yckart's comment and suggest using localStorage.

The support is pretty good (shown here) and unless you need to support IE7 or less you should be ok.

You can set and retrive data like this:

localStorage.varName = 'bling';
var myVal = localStorage.varName;
// or:
localStorage['a little more flexibility'] = 'bling';

To use this, you could do the following:

<script type="text/javascript">
    if (localStorage && localStorage.country) {
        location = localStorage.country;    
    }

    function formChanged(form) {
        var val = form.options[form.selectedIndex].value;
        if (val !== 'non-value') {
          if (localStorage) {
            localStorage.country = val;
          }
          location = val;
        }
    }
</script>

<FORM NAME="form1">
  <select onchange="formChanged(this);" NAME="country" SIZE="1">
    <OPTION VALUE="non-value">Select Country
    <OPTION VALUE="chile">Chile
    <OPTION VALUE="colombia">Colombia
    <OPTION VALUE="bolivia">Bolivia
  </select>
</FORM>

http://jsfiddle.net/K4Jkc/

An approach that would be a little more conservative would be to compare the value stored in localStorage (if there is one) to options in the select-list before doing the redirect, as shown in this jsFiddle:

http://jsfiddle.net/K4Jkc/1/