0

Why this program doesn't work when i try declaring let inputError globally like the rest lets or I write let before inputError in function? I don't understand why it only works when it is declaring inside the function without let, const.

let ul_var; 
let shoppingArray = ["Mleko", "Jajka", "Piwo"]; 
let new_item_form_var;

>>>> let inputError; <<<< //without it works

document.addEventListener("DOMContentLoaded", () => {
  ul_var = document.getElementById("shopping");
  >>>> let <<<< inputError = document.getElementById('inputError');
  new_item_form_var = document.getElementById("new_item_form");


  new_item_form_var.addEventListener("submit", (event) => {
    event.preventDefault();
    let input = event.target.elements[0];

    if (input.value.length > 2 && !input.value.startsWith(' ')) {
      addListItem(input.value);
      input.value = '';
      input.classList.remove('input-danger');
      inputError.innerText = ''; 
    } else {
      inputError.innerText = 'Nazwa nie spelnia kryteriow';
      input.classList.add('input-danger') 
    }
  });

  for (let x of shoppingArray) {
    addListItem(x);
  }

});

function addListItem(y) {
  let li_var = document.createElement("li"); 
  li_var.innerText = y; 
  ul_var.appendChild(li_var);
}
Monfear
  • 11
  • 3
  • Any error message in the console ? – Cid Apr 23 '20 at 09:22
  • Does this answer your question? [Reassigning a variable using 'let' is not working](https://stackoverflow.com/questions/47807204/reassigning-a-variable-using-let-is-not-working) – Justinas Apr 23 '20 at 09:23
  • Read the above suggestion and see that you basically answered your own question. – Shane_Yo Apr 23 '20 at 09:34

1 Answers1

0

If you have one let inputError then you can't have another one, because you can't declare the same variable several times. You should instead write:

let inputError;

document.addEventListener("DOMContentLoaded", () => {
  ul_var = document.getElementById("shopping");
  inputError = document.getElementById('inputError'); // no let

or this, if you don't use inputError outside of the event listener:

// no 'let inputError;'

document.addEventListener("DOMContentLoaded", () => {
  ul_var = document.getElementById("shopping");
  let inputError = document.getElementById('inputError');
Nino Filiu
  • 16,660
  • 11
  • 54
  • 84