Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 class="form-control" id="quote-text" name="quote-text" rows="3"></textarea>
  <button type="submit" class="btn btn-primary">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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading