JoeyD JoeyD - 1 year ago 89
Javascript Question

Cancel a previous Jquery Form Submit on Key Up

I have a search form that I am trying to do dynamic type down on. On keyup I am submitting the form. However I am running into issues with large data sets. The issue is that each form submit always returns a result and that result is always inserted into the DOM. For example when I type in the 4th character on keyup it submits the form and returns 100 matching results. When typing in the 5th character it returns only 2 results. The execution time of the 5th character returns faster then the 4th. So what ends up happening is it paints the 2 results in the DOM and then the 4th returns and paints the 100 results into the DOM.

Is there a way to cancel or ignore the previous form post results if a keyup event happens after the submit? Here is the Form and the submit via javascript

@using (Ajax.BeginForm(new AjaxOptions
HttpMethod = "get",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "Breweries"
<input id="brewerySearchInput" class="form-control page-header-input" placeholder="Search" type="search" name="searchTerm" />

$("#brewerySearchInput").keyup(function () {
if ($(this).val().length >= 3 || $(this).val().length == 0) {

Answer Source

I think yours is a classic case of using debounce function.

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.

You will be making too many unnecessary backend requests otherwise. Check it out