0

Both in the case I enter a string and in the case I leave the input box blank, I get the console.log("Something's wrong!"); The console.log of my fieldObj is in both cases shown empty.

I tried check if the content of an input-field is empty:

CODE:

let fieldObj = document.getElementById("newListItem").value;
let button = document.getElementById("addItem");

button.addEventListener("click", function() {
  if (fieldObj != "") {
    console.log(fieldObj);
    console.log("Everything ok!");
  } else {
    console.log(fieldObj);
    console.log("Something's wrong!");
  }

}, false);
<input id="newListItem" type="text" />
<button id="addItem">Add</button>

I'd appreciate any help!

1 Answer 1

4

This is because you set fieldObj as soon as the page loads, so it will be set as "" and never change.

You need to update the value inside the click listener :

const button = document.getElementById("addItem");

button.addEventListener("click", function() {
  const fieldObj = document.getElementById("newListItem").value;
  if (fieldObj !== "") {
    console.log(fieldObj);
    console.log("Everything ok!");
  } else {
    console.log(fieldObj);
    console.log("Something's wrong!");
  }

}, false);
<input id="newListItem" type="text" />
<button id="addItem">Add</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.