Why doesn't my function output the correct string?

After learning the basics of html and CSS I’m currently following SuperSimpleDev tutorial on JavaScript.
In my web page, I’m supposed to see the following display :
Get groceries
Wash car
Make dinner

But I just got ‘Get groceries’ 3 times instead.
Here is my code.

let todo1 = 'Get groceries';
let todo2 = 'Wash car';
let todo3 = 'Make dinner';

function addTodo(todoTitle) {
  let element = document.createElement('div');
  element.innerText = todo1;
  document.body.appendChild(element);
}

addTodo(todo1);
addTodo(todo2);
addTodo(todo3);
<button>Press meeeeee</button>

>Solution :

Your code is set to always add todo1. Instead, add whatever the value of the function argument is.

let todo1 = 'Get groceries';
let todo2 = 'Wash car';
let todo3 = 'Make dinner';

function addTodo(todoTitle) {
  let element = document.createElement('div');
  element.innerText = todoTitle;  //  <-- You were always adding todo1 here
  document.body.appendChild(element);
}

addTodo(todo1);
addTodo(todo2);
addTodo(todo3);
<button>Press meeeeee</button>

Also, your code should probably run when the button is clicked, but right now, you aren’t doing anything with the button. So here’s the code that will work based on a button click.

let todo1 = 'Get groceries';
let todo2 = 'Wash car';
let todo3 = 'Make dinner';

// Set the button up to invoke a function when clicked
document.querySelector("button").addEventListener("click", function(){
  // This is just an example of how a user could select different choices
  let choice = prompt('Enter 1-3 for the various choices.');
  
  // switch allows you to test a single value for many possible
  // outcomes and act accordingly for each. Prepending + to a string
  // that holds a numeral implicitly converts it to a number.
  switch(+choice){
    case 1:
      addTodo(todo1);
      break;
    case 2:
      addTodo(todo2);
      break;
    case 3:
      addTodo(todo3);
      break;
    default:
      addTodo("You didn't enter a valid choice");
  }
})

function addTodo(todoTitle) {
  let element = document.createElement('div');
  element.innerText = todoTitle;  //  <-- You were always adding todo1 here
  document.body.appendChild(element);
}
<button>Press meeeeee</button>

Leave a Reply