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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.