0

I have page on my site. Let's say it's:

https://example.com/consulting/#ref/testing

and on that link there is input field:

<input type="text" value="" id="input19" />

So I want to do the following action:

Split the URL in the browser, so I had last word from the link (in this case it's "testing"). I'm using following script for this:

var url = document.URL;
var match = url.match(/([^/]*)$/);
console.log(url);
console.log(match);

That script will give me last word from the link in this example it's "testing" and I need this word ("testing") to be written in cookies before browser is closed and from cookies it should be inserted in the above mentioned input field with the id "input19".

This cookie should not be changed before it's deleted. When user will browse the site and after returns to the above mentioned page value from cookie should be inserted in the input field as well.

Could you give me a solution on how I can achieve this?

Sergi Khizanishvili
  • 537
  • 1
  • 7
  • 16

1 Answers1

0

I would recommend something like this to achieve what you are going to do.

See also: set and get cookies with javascript - stackoverflow

window.onbeforeunload = function(){
  var input19 = $('#input19').val();
  createCookie(input19,'your-site-cookie',7);
};

window.onload = function(){
  var inputx = readCookie('your-site-cookie');
  if (inputx) {
    $('#input19').attr("value", inputx);
  }
};

function createCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

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;
}
Community
  • 1
  • 1
Felix Haeberle
  • 1,530
  • 12
  • 19