Friday, 30 November 2018

Check array for duplicate values if cookies aren't set, don't check if cookies are set

I'm working on a chatroom page where you first set your username and it sets the username value inside cookies. after this it loads different input boxes where you can send messages from in realtime. At this point you can reload the page and it will give you a pop-up which will display a welcome back message with the name value saved inside the cookies, which will also just set it as the username again and load the chatting page.

The problem is that I want to be able to prevent multiple duplicates of a name to be set from the username setting input field, but allow the username be set multiple times inside the array via cookies.

this function sets the original username:

//index.html
function setUsername() {
    var textbox = document.getElementById("name");
    var txtboxval = textbox.value;
    if(textbox.value.length <= 20 && textbox.value.length >= 4){
      socket.emit('setUsername', document.getElementById('name').value);
      setCookie("username", txtboxval, 30);
      socket.on('userExists', function(data) {

      });
    }
    else{
        alert("The name has to be at least 4 characters long");
        return false;
      }
    };

and these two set it on cookie load:

  //index.html
  function setUsername2() {
    var nimi = getCookie('username');
    socket.emit('setUsername', nimi);
  }

  function checkCookie() {
      var user = getCookie("username");
      if (user != "") {
          alert("Welcome again " + user);
          setUsername2();
          document.body.innerHTML = '<div class="wrapper"><div class="messagebox"><input type = "text" id = "message" placeholder = "Write your message here">\
          <button type = "button" id="sending" name = "button" onclick = "sendMessage()">Send</button></div>\
          <div id = "message-container"></div></div>';
      }
    }

now this here actually sets the username into the array where it digs it from on the index.html page:

  //app.js
  users = [];
  io.on('connection', function(socket){
    console.log('an user connected');
    console.log(users);
    socket.on('setUsername', function(data) {
      console.log(data);

        users.push(data);
        socket.emit('userSet', {username: data});
        console.log(users);
  });

I would like this piece of code to run when first setting the username, but not when it loads from cookies:

//app.js
if(users.indexOf(data) > -1) {
          socket.emit('userExists', data + ' Username is already taken.');
        } else {
          users.push(data);
          socket.emit('userSet', {username: data});
          console.log(users);
        }

Is there something I'm missing on why I can't get it to work as I would like it to? If something is unclear please ask.



from Check array for duplicate values if cookies aren't set, don't check if cookies are set

No comments:

Post a Comment