0

I'm working on an app that makes fetch calls to a dictionary API based on the user's input. The problem is, I can't seem to get the input value from the search bar. Currently, all that's being logged to the console is an empty string. I currently have my code inside of a DOMContentLoaded event listener. When I take my code out of the DOMContentLoaded function, I am getting a null value returned. This is incredibly straightforward but I can't seem to figure out what is getting muddled here. Here is the code;

window.addEventListener('DOMContentLoaded', () => {
    const searchBar = document.getElementById('search-bar');
    const userInput = searchBar.value;
    const searchButton = document.getElementById('search-button');

    const test = () => console.log(userInput);
    
    searchButton.addEventListener('click', test);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script src="app.js"></script>

    <title>Dictionary</title>
</head>
<body>
    <h1>Dictionary</h1>

    <input type="text" id="search-bar" placeholder="Find a definition"/>
    <button id="search-button">Search</button>

    <div id="results-area">

    </div>
</body>
</html>

Thanks for the help.

1 Answer 1

3

The issue was you're getting always the first value of input which is empty, to get the new value call searchBar.value on the click of button.

window.addEventListener('DOMContentLoaded', () => {
  const searchBar = document.getElementById('search-bar');
  
  const searchButton = document.getElementById('search-button');

  const getInputValue = () => {
    let userInput = searchBar.value;
    console.log(userInput);
  }

  searchButton.addEventListener('click', getInputValue);
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <script src="app.js"></script>

  <title>Dictionary</title>
</head>

<body>
  <h1>Dictionary</h1>

  <input type="text" id="search-bar" placeholder="Find a definition" />
  <button id="search-button">Search</button>

  <div id="results-area">

  </div>
</body>

</html>

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

1 Comment

Ah, very simple indeed! I appreciate the help.

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.