How do you conditionally display/hide one of two forms with a live search in Django?

I have two forms:

from django import forms
from .models import Entity, Quote

class EntityForm(forms.ModelForm):
    class Meta:
        model = Entity
        fields = ['name', 'website', 'contact']

class QuoteForm(forms.ModelForm):
    class Meta:
        model = Quote
        fields = ['entity', 'text', 'notes']

Initially on page load only the entity name field is displayed along with the whole quote form. The website and contact fields should not be displayed.

The user fills in the entity name field. We do a live search to get all values in the entity model that are similar to help them fill in the form. If no results are returned from their input text, the website and contact fields should now be displayed.

The live search functionality is fairly simple to implement, however I'm struggling with the hide/unhide functionality and could use some help.

The page initially loads the quote text and I'm not sure why. Similarly, when I fill in the entity field with strings I know that aren't in the database there's no hide/unhide toggle.

<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">
  <div class="form-group">
    <label for="quote-text">Quote Text:</label>
    <textarea class="form-control" id="quote-text" name="quote-text" rows="3"></textarea>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

  <script>
    function searchEntities() {
      const entityName = document.querySelector('#entity-name').value;
      fetch(`/search-entities/?entity_name=${entityName}`)
        .then(response => response.json())
        .then(entities => {
          const searchResults = document.querySelector('#search_results');
          searchResults.innerHTML = '';
          entities.forEach(entity => {
            const p = document.createElement('p');
            p.innerHTML = entity.name;
            searchResults.appendChild(p);
          });
        });
    }

    const entityNameField = document.getElementById("entity-name");
    const quoteTextField = document.getElementById("quote-text");

    entityNameField.addEventListener("blur", async function() {
        const entityName = entityNameField.value;
        const response = await fetch(`/api/entities/?entity_name=${entityName}`);
        const entities = await response.json();

        if (entities.length === 0) {
            quoteTextField.style.display = "none";
        } else {
            quoteTextField.style.display = "block";
        }
});

</script>
Back to Top