skip to Main Content

I am trying to figure out how to display an alert box saying "Please input a value" when a button is clicked and there is no text in the input box. Here is what I have tried so far:

const checkButton = document.getElementById("check-btn");
const textInput = document.getElementById("text-input");
const result = document.getElementById("result");

if (textInput.value = "" && checkButton.click()){
  window.alert("Please input a value")
}

This is not working though when i test it on freeCodeCamp’s test. What am I doing wrong?

const checkButton = document.getElementById("check-btn");
const textInput = document.getElementById("text-input");
const result = document.getElementById("result");

if (textInput.value = "" && checkButton.click()){
  window.alert("Please input a value")
}

2

Answers


  1. You need to attach the event listener to the button by id and check the input value within the event listener.

     document.getElementById('check-btn').addEventListener('click', function(){
        let inputValue = document.getElementById("text-input").value;
        if (inputValue && inputValue.trim() === '') {
            // Display an alert if the input is empty
            alert('Please input a value');
        } else {
            // Proceed with your logic for non-empty input
        }
    });
    
    Login or Signup to reply.
  2. Theres 2 problems. So first off you can’t just put checkButton.click() you have to put a event listener like checkButton.addEventListener() so it checks all the time when a button is pressed. Next, your if statement is wrong because there is supposed to be 2 equal signs not one.

    const checkButton = document.getElementById("check-btn");
    const textInput = document.getElementById("text-input");
    const result = document.getElementById("result");
    checkButton.addEventListener("click", function(){
      if (textInput.value == ""){
        window.alert("Please input a value");
      }
    });
    <input id = "text-input">
    <button id = "check-btn">check</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search