Search code examples
javascripthtml

Trying to check for empty value in input


I have an input box that changes another paragraph in my site with JavaScript. It works flawlessly, except for the fact that when I enter nothing in the input, it blanks out the paragraph.

I don't want this to happen. I've tried almost every piece of code I've found online to fix this issue but nothing has worked.

<div class="tasklist">
   <p id="task1" style="color:#d3d3a3">You don't have any tasks.</p>
</div><br>
<script>
  const element = document.getElementById("task1");
  var task = document.input["task"].value;
  function getInputValue() {
    let value = document.getElementById("task").value;
    element.innerHTML = (value);
    document.getElementById("task1").style.color = "white";
  }
</script>
Enter a task:<br>
<input type="text" id="task" name="task" placeholder="Pay Bills">
<button onclick="getInputValue();" onclick="changeColor()">+ Add</button>

Solution

  • <div id="tasklist">
      <p id="msg" style="color:red">You don't have any tasks.</p>
    </div>
    <br>
    
    <script>
      const element = document.getElementById("msg");
      element.style.display = "none";
    
      function add() {
        let value = document.getElementById("task").value;
    
        if (value && value.trim() != "") {
          document.getElementById("task").value = "";
          element.style.display = "none";
          const taskContainer = document.getElementById('tasklist');
    
          const task = document.createElement('p');
          task.textContent = value;
          taskContainer.append(task)
        } else {
          element.style.display = "block";
        }
    
      }
    </script>
    Enter a task:<br>
    <input type="text" id="task" name="task" placeholder="Pay Bills">
    <button onclick="add();">+ Add</button>