I think this is a JavaScript problem but could be wrong.
I have a JavaScript routine that searches a database for typed characters in an input text box and it works fine…
Until the enter is pressed and it clears the search keys
How can I prevent the enter key clearing the search?
Form Stuff
<form action="?" method="get">
<div class="p42">
<header>
<br>
<label class="fll fgy XXXfsl fwb p42" for="searchTerm">
Search:
</label>
<input
id="searchTerm"
class="w55 p42"
type="text" name="searchTerm"
placeholder="characters ONLY - NOT ENTER"
>
</header>
</div>
</form>
JavaScript
const searchTermElem = document.querySelector('#searchTerm');
// const searchResultElem = document.querySelector('#searchResult');
const searchResultElem = document.querySelector('#livesearch');
searchTermElem.focus();
searchTermElem.addEventListener('input', function (event)
{
search(event.target.value);
});
const debounce = (fn, delay = 888) =>
{
let timeoutId;
return (...args) => {
// cancel the previous timer
if (timeoutId) {
clearTimeout(timeoutId);
}
// setup a new timer
timeoutId = setTimeout(() => {
fn.apply(null, args)
}, delay);
};
};
//=======================================================================
const search = debounce(async (searchTerm) =>
{
// if the search term is removed, reset the search result
if (!searchTerm) {
// reset the search result
searchResultElem.innerHTML = '';
return;
}
try {
searchResultElem.innerHTML = '';
// make an API request
// const url = `https://en.wikipedia.org/w/api.php?action=query&list=search&prop=info|extracts&inprop=url&utf8=&format=json&origin=*&srlimit=10&srsearch=${searchTerm}`;
const url = 'AJAX-0048.php?q=' + searchTerm;
const response = await fetch(url);
const result = await response.text();
// alert(result);
console.log(result);
searchResultElem.innerHTML = result;
} catch (error) {
console.log(error);
}
});
const stripHtml = (html) => {
let div = document.createElement('div');
div.innerHTML = html;
return div.textContent;
};
const highlight = (str, keyword, className = "highlight") => {
const hl = `<span class="${className}">${keyword}</span>`;
return str.replace(new RegExp(keyword, 'gi'), hl);
};
const generateSearchResultHTML = (results, searchTerm) => {
return results
.map(result => {
const title = highlight(stripHtml(result.title), searchTerm);
const snippet = highlight(stripHtml(result.snippet), searchTerm);
return `<article>
<a href="https://en.wikipedia.org/?curid=${result.pageid}">
<h2>${title}</h2>
</a>
<div class="summary">${snippet}...</div>
</article>`;
})
.join('');
}