Setting form data to a cookie value in javascript

3.4k Views Asked by At

I am trying to set form data to a cookie value
Hare is my code:

The html :

<form method="POST" action="#" id="address-form">
  <select name="city">
     <option value="a city">A City</option>
  </select>
  <select name="pincode" id="pincodes">
     <option value="">Select Pincode</option>
     <option value="pin1">pin1</option>
     <option value="pin2">pin2</option>
   </select>
   <br><br>
   <input type="submit">
 </form>

JS:

//set the cookies
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// get the cookies
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
// check the cookies
function checkCookie() {
    var user = getCookie("username");

    // function mmm() {
    //     $("form").submit(function (e) {
    //         e.preventDefault();
    //         user = $('#pincodes').val();
    //     });
    //     return user;
    // }

    if (user !== "") {
        console.log("Pincode is: " + user);
    } else {
        openModal();
        user = $("#pincodes option:selected").val();
        console.log("Pincode not set");
        if (user !== "" && user !== null) {
            setCookie("username", user, 365);
        }
    }
}
//execute the cookie function
checkCookie();

But when I am refreshing the page it is saying that "Pincode not set" and opening the modal every time and cookie is not setting.

1

There are 1 best solutions below

0
On BEST ANSWER

You can check this fiddle: jsfiddle.net/bharatsing/wga5t2jw/

$( "#address-form" ).submit(function( event ) {
    var user = $("#pincodes option:selected").val();        
    if (user !== "" && user !== null) {
        setCookie("username", user, 365);
    }
    event.preventDefault();
});