Home > OS >  How do I update this form field so it stays hidden on page load?
How do I update this form field so it stays hidden on page load?

Time:01-31

I have this form in my Django project. On page load it should only show the entity name, but it's showing both the entity-name and quote-text fields. The page should only show the quote-text field when the entity-name is not in the database.

The toggle works for all cases except page load. It's the line if (entities.length === 0) I need to update but I'm not sure what to update it to.

<form>
  <label for="entity-name">Entity Name:</label>
  <input type="text" id="entity-name" name="entity-name" onkeyup="searchEntities()">
  <div id="search_results"></div>
</form>

<form id="quote-form">
  <label for="quote-text">Quote Text:</label>
  <textarea  id="quote-text" name="quote-text" rows="3"></textarea>
  <button type="submit" >Submit</button>
</form>

<script>


  function searchEntities() {
    const entityName = document.querySelector('#entity-name').value;
    console.log('hi');
    console.log(entityName);
    fetch(`/search-entities/?entity_name=${entityName}`)
      .then(response => response.json())
      .then(entities => {
        const searchResults = document.querySelector('#search_results');
        searchResults.innerHTML = '';
        if (entities.length === 0) {
          // Show the quote field
          document.querySelector('#quote-form').style.display = 'block';
        } else {
          entities.forEach(entity => {
            const p = document.createElement('p');
            p.innerHTML = entity.name;
            searchResults.appendChild(p);
          });
          // Show the quote field
          document.querySelector('#quote-form').style.display = 'none';
        }
      });
  }

</script>

CodePudding user response:

Try this and see if it works, this will run your script after the page is loaded and ensures the whole DOM is loaded first and then execute the script:

<script>
  ....

  window.onload = function() {
    searchEntities();
  };
</script>
  • Related