Kogden
Kogden

Reputation: 46

Uncaught TypeError: Cannot read property 'toLowerCase' of null

This prompt was working perfectly well up until I updated some other javascript. I don't know how I messed it up. This function is declared in the body tag to run 'onload'.

function funcPrompt() {
   var answer = prompt("Are you a photographer?", "Yes/No");
   answer = answer.toLowerCase();

if (answer == "yes") {
    alert('Excellent! See our links above and below to see more work and find contact info!');
}
else if(answer == "no") {
    alert('That is okay! See our links above and below to learn more!');
}
else if(answer == null || answer == "") {
    alert('Please enter an answer.');
    funcPrompt();
}
else {
    alert('Sorry, that answer is not an option');
    funcPrompt();
}
}

Now suddenly I'm getting this error and the prompt won't appear.

Upvotes: 2

Views: 22433

Answers (3)

vivekagarwal277
vivekagarwal277

Reputation: 585

Not certain why you are getting a null but if you are trying to avoid the null, use this:

answer = (answer?answer:'').toLowerCase();

Upvotes: 7

Yordan Ivanov
Yordan Ivanov

Reputation: 580

In your case, better use a confirm instead of a prompt

function funcConfirm() {
  var answer = confirm("Are you a photographer?");

  if (answer === true) {
    alert('Excellent! See our links above and below to see more work and find contact info!');
  } else {
    alert('That is okay! See our links above and below to learn more!');
  }
}

funcConfirm();

Upvotes: 0

Rayon
Rayon

Reputation: 36609

If we click on Cancel, prompt will return null and one can not apply toLowerCase on null(Will cause an exception!)

Add a condition answer===null before all other conditions and return to stops the execution of a function

function funcPrompt() {
  var answer = prompt("Are you a photographer?", "Yes/No");
  if (answer === null || answer === "") {
    alert('Please enter an answer.');
    funcPrompt();
    return;
  }
  answer = answer.toLowerCase();
  if (answer == "yes") {
    alert('Excellent! See our links above and below to see more work and find contact info!');
  } else if (answer == "no") {
    alert('That is okay! See our links above and below to learn more!');
  } else {
    alert('Sorry, that answer is not an option');
    funcPrompt();
  }
}
funcPrompt();

Upvotes: 3

Related Questions