0

I have this codes wherein at the start of the conversation, names were generated randomly but what i wanted to do is that, the generated name will retain when i refresh the page. Any idea how can i do this?

function replaceName() {

    var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
    var randomIndex = Math.floor(Math.random() * textArray.length); 
    var randomElement = textArray[randomIndex];
    var text1 = "Hi, I'm ";
    var text2 = ", How can i help you?";
    var text3 = text1.concat(randomElement,text2); 

    document.getElementById("demo").innerHTML = text3;
}

replaceName();
<p id="demo">Hi, I'm Joey, How can i help you?</p>
Ali Turki
  • 1,265
  • 2
  • 16
  • 21

3 Answers3

0

You can use localStorage.getItem('name') to get the selected name on refresh.

function replaceName() {
  var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
  var randomIndex = Math.floor(Math.random() * textArray.length);
  var randomElement = textArray[randomIndex];
  localStorage.setItem('name', randomElement);
  var text1 = "Hi, I'm ";
  var text2 = ", How can i help you?";
  var text3 = text1.concat(localStorage.getItem('name'), text2);
  document.getElementById("demo").innerHTML = text3;
}

replaceName();
<p id="demo">Hi, I'm Joey, How can i help you?</p>
Sankar
  • 6,908
  • 2
  • 30
  • 53
0

try using Cookies :

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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 "";
}


function replaceName() {
var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
var randomIndex = Math.floor(Math.random() * textArray.length); 
var randomElement = textArray[randomIndex];

var storedName= setCookie('username',randomElement,30); // set cookie name ,value, extime
var getName  =  getCookie('username'); //get cookie value by name and store it in getname var  
var text1    = "Hi, I'm ";
var text2    = ", How can i help you?";
var text3    = text1.concat(getName,text2);
document.getElementById("demo").innerHTML = text3;
}

replaceName();
<p id="demo">Hi, I'm Joey, How can i help you?</p>
0

On first glance, other answers don't handle page load (maybe they do and I'm missing something...). Both localStorage or cookies are fine, it doesn't make much difference which you pick for this problem. You should try both, just for practice.

I added a delete cookies button, for your convenience (Edit: it doesn't delete the cookie, just sets it to empty string)

<script>
// either we can read a cookie
// or the cookie is empty -> then we pick a random name and set is as cookie
window.onload = function() {
  var randomname = getCookie('randomname');
  if(randomname != '') {
    setName(randomname);
  }
  else {
    setCookie('randomname', replaceName());
  }
}

function replaceName() {
  var textArray = ['Mark', 'Jane', 'Aldrin', 'Len'];
  var randomIndex = Math.floor(Math.random() * textArray.length); 
  var randomElement = textArray[randomIndex];
  setName(randomElement);
  return randomElement;           // we would like to know the name, just the name, so we can store it somewhere
}
// I take this code out of replaceName() and set it in a separate function.
// so you can use it both for setting the name from cookie as for the random name
function setName(name) {
  var text1 = "Hi, I'm ";
  var text2 = ", How can i help you?";
  var text3 = text1.concat(name, text2);
  document.getElementById("demo").innerHTML = text3;
}

function deleteCookies() {
  setCookie('randomname', '');
}

// Get and Set cookie; @see https://www.w3schools.com/js/js_cookies.asp
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=/";
}
function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.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 "";
}
</script>
<div id="demo"></div>
<input type="button" value="delete cookie" onclick="deleteCookies()"/>

What I would advise: try using better names for functions; make sure the name of the function discribes what you intend to do. You notice I cut your function in half, I made two functions out of it. Since setName is needed both for a new name and for a name that was saved in a cookie or localstorage, it's better to have it as a separate function

Emmanuel Delay
  • 3,619
  • 1
  • 11
  • 17