Get parameter value from cookie

Hi, I have a little problem. Currently, I have 2 parameters stored in the browser cookie, which are ADV and LOC ... Now I have a page with the form, and the form received two hidden fields:

<input type="hidden" name="adv" value="" />
<input type="hidden" name="loc" value="" />

I need to get adv and loc values ​​from a cookie and store them in hidden field forms ... How can I do this, please? Thanks

+3
source share
1 answer

document.cookie will provide you with all cookies in the following format:

'adv=adv_val; loc=loc_val;'

To get the value from the cookie, you can use this function (from quirksmode ):

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

To fill in the hidden fields, you can loop all the hidden fields and get their cookies:

function hiddenCookies(){
  var inputs = document.getElementsByTagName('input');
  for(var i = 0; i < inputs.length; i++){
      var element = inputs[i];
      if(element.getAttribute('type') == 'hidden'){
          element.value = readCookie(element.name);
      }
  }
}

<body> onload.

<body onload="hiddenCookies()">

jQuery:

$(function(){
  $('input:hidden').each(function(i,v){
      v.value = readCookie(v.name);
  });
});
+5

Source: https://habr.com/ru/post/1792841/


All Articles