How to ignore ENTER key from clearing dynamic search

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 :frowning:

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: &nbsp; 
          </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('');
}

Online demo

Hi there John,

adding something like this…

	d.querySelector('form').addEventListener( 'submit',
		function(e){ 
			e.preventDeault();
		},false);

…to an appropriate position in the code
should effect a cure to your problem. :winky:

coothead

3 Likes

Hi @coothead,

Many thanks for the suggestion it was a great help.

I already had a JavaScript function addEventListener(…) and failed miserably trying to add e.preventDefault();, etc. Also prevented the search from working so…

…investigated further and managed to add the following script:

  <!-- 
    added onsubmit= 'return trapEnterKey("Pressing ENTER \n\t is \n unnecessary")'
  -->
  <form 
      action="?" 
      method="get" 
      onsubmit= 'return trapEnterKey("Pressing ENTER \n\t is \n unnecessary")'
    >

Also added the following JavaScript function trapEnterKey(…)

//======================================================
function trapEnterKey( msg )
{
  alert(msg);

  return false;
}

It now works a treat and also adds an informative popup JavaScript Alert box.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.