Akanimoh Samuel Obot
Akanimoh Samuel Obot

Reputation: 120

Attaching username given and removing undefined from an Alert box

I have tried to make my username that I enabled in my html page to be attached to welcome again! but the prompt box keeps returning welcome again!undefined onsubmit instead of welcome again!Akan for example

My setCookie and getCookie functions are working just fine

This are the html and Js codes which concern this problem, respectively

<form action="Home.html" method="form" onsubmit="return checkCookie()">
  Name: <input type="text" name="username" size="40"\>
  <input type="submit" value="submit" \>
<\form>
function setCookie(cname,cvalue,exdate) {
    let exd=new Date();
        exd.setTime(exd.getTime()+ (exdate*24*60*60*1000));
    let expires= 'expires=' + exd.toUTCString();

    document.cookie=cname + '=' +cvalue +';' +expires +';path=/';  
}

function getCookie(cname) {
    if (document.cookie.length>0) {
        cstart=document.cookie.indexOf(cname + '=');
        if (cstart !=-1) {
            cstart= cstart+ cname.length+1
            cend= document.cookie.indexOf(cstart ,';');
        if (cend==-1) {
            cend=document.cookie.length;
        return 
            unescape(document.cookie.substring(cstart,cend));
        }
        }
        return "";
    }
}

function checkCookie() {
    let username=getCookie('username').value;

    if (username!='') {
        alert('Welcome again!'+ username);
    } else {
        username=prompt('Please enter your name:' ,'');
        if (username!='') {
            setCookie('username',username,365);
        }
    }
}

Your help will be appreciated

Upvotes: 0

Views: 46

Answers (1)

Sergio Belevskij
Sergio Belevskij

Reputation: 2947

First: getCookie is undefined. Second: form in this example is not needed.

function checkCookie() {
  let username = document.querySelector('input[type="text"]').value;

  if (username != '') {
    alert ('welcome again!' + username);
    document.querySelector('#my-form').submit();
  } else {
    username = prompt('Input your name:', '');
    if (username != '') {
      setCookie('username', username, 365);
    }
  }
}
<form id="my-form">
  Name: <input type="text" name="username" size="40"/>
  <input type="button" onclick="checkCookie()" value="submit" />
</form>

Upvotes: 1

Related Questions