Search code examples
javascripthtmlformscookiesdropdown

JS Save cookie on form submit


I'm trying to create a simple form that pops up (i'll be putting the below code into a bootstrap modal) and asks a user to select their location from a drop down list.

I think I'm almost there with this code however the cookie value is always stored as "undefined" when i click submit.

<html>
<head>
    <script>
function setCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();

    if (!nDays) 
        nDays=1;

    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}

  </script>
</head>
<body>
    <form onsubmit="setCookie('location', this.value, 365);">
    <select>
        <option value="location1">Location 1</option>
        <option value="location2">Location 2</option>
    </select>
    <input type="submit" value="Submit">
</form>
</body>   
</html>

Any advice on how I can get it to store the cookie value from the dropdown?


Solution

  • As David put it in his comment, form does not return the value of select, so alternatively you can do this:

    function setCookie(cookieName, cookieValue, nDays) {
        
        var today = new Date();
        var expire = new Date();
    
        if (!nDays) 
            nDays=1;
      console.log('cookieName: ' + cookieName)
      console.log('coockieValue: ' + cookieValue)
      console.log('nDays: ' + nDays)
        expire.setTime(today.getTime() + 3600000*24*nDays);
        // document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
        return false
    }
    <form onsubmit="javascript:return setCookie('location', this.querySelector('select').value, 365);">
        <select>
            <option value="location1">Location 1</option>
            <option value="location2">Location 2</option>
        </select>
        <input type="submit" value="Submit">
    </form>

    Note: I put a return in the function so that we can see what is returned in the function parameters