2016-12-31 3 views
0

Я пытаюсь установить данные формы к значению печенья
Hare мой код:Установка данных формы в значение куки в JavaScript

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(); 

Но когда я обновляю страницу, это говорит о том, что «Пинко не устанавливать "и каждый раз открывать модальный режим, а cookie не устанавливается.

+0

Вы смотрели в coockie.js - https://github.com/js-cookie/js-cookie – soundslikeodd

ответ

0

Вы можете проверить эту скрипку: 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(); 
}); 
Смежные вопросы