Activate the search function once the user has finished entering text

Currently facing the following issue:

Within my JavaScript file, I have the below code snippet,

    termChange(evt) {
        this.rows = [];
        this.searchTerm = evt.target.value;
        this.getCases();
    }

This section of code clears out the rows returned after a search, captures the search term from the event, and then triggers the getCases function.

The getCases function is an asynchronous operation that retrieves data from our server. The HTML includes onChange={termChange}. However, the problem arises as every keystroke prompts the function to fire 8 times during searching. This results in undesired duplicate search results. I am seeking a way for this event to trigger only after the user finishes typing. I've attempted using setTimeouts and debounce techniques but have been unsuccessful in resolving the issue. Any assistance with this matter would be greatly appreciated. Thank you!

The goal is for the search to automatically initiate once the user has finished typing, without requiring any additional actions or clicks.

    debounce(func, wait, immediate) {
        var timeout;
        return function executedFunction() {
          var context = this;
          var args = arguments;
          var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
            };
          var callNow = immediate && !timeout;
          clearTimeout(timeout);
          timeout = setTimeout(later, wait);
          if (callNow) func.apply(context, args);
        };
    }

Here is the debounce function implementation. However, when attempting to use it like so:

    handleTermChange = this.debounce(this.termChange(), 1000, false);

An error is thrown stating that the target is undefined. As a result, the event is not passed through, and I have been unable to find a solution to make it functional. This obstacle persists with using the debounce method effectively.

Answer №1

Utilizing debounce is essential for achieving the desired outcome. Perhaps adjusting the timer could be beneficial, or there may be an issue with the debounce function itself?

In my experience, I have found that a 250ms timer works well for the search box on the website I oversee. However, if dealing with a slower API or significant page modifications, opting for a longer timer may be more appropriate.

Additionally, verifying that the input has actually changed is crucial. One method to achieve this is by storing the previous search term and terminating the search process if the new input matches the old input.

Answer №2

Consider implementing the on blur event instead of triggering an event every time the user inputs text.

Answer №3

To accomplish this, you can make use of the onkeyup event listener.

HTML:

<input type="text" onkeyup="handleInput(event)">

JS:

var timer = null;
function handleInput(e) {
    clearTimeout(timer);
    timer = setTimeout(function () {
          //Add your code here
    }, 500);

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting $scope.$on unit testing - event not getting detected

In one of my controllers, I have implemented a simple $scope.$on function: app.controller('MyController', function($scope) { $scope.$on("myBroadRcvr", function(event, data) { $scope.name = data.name; $scope.empID = data.empID ...

Utilizing Font Awesome icons dynamically presents challenges when integrating with SVG & JavaScript

Recently, I started using the new JS&SVG implementation of font-awesome's v5 icons. It seems to be working perfectly for icons (such as <i class='fas fa-home'></i>) that are already present in the DOM at page load. The <i& ...

Interactions with the mouse while using the window.alert and window.confirm features

Currently, I have developed a custom drag method that utilizes mousedown, mouseup, and mousemove events. This method is defined as move(). $(document).on('mousedown', function() {drag = true }); $(document).on('mouseup', function() {dr ...

Check to see if the menu item exceeds the allotted space, and if so, display the mobile menu

Currently, I am in the process of creating a unique responsive menu for my website that I think will need some JavaScript implementation. My skills with JavaScript are not very strong, so I am looking for guidance, code examples, or resources that can assi ...

There was a SyntaxError that caught me by surprise in my Javascript code when it unexpectedly encountered

I have been encountering an error in my code consistently, and I am struggling to comprehend why this is happening. The problematic area seems to be in line 29 of my Javascript file. HTML <link href="Styles12.css"; type="text/css" rel="stylesheet"> ...

What is the process for creating instant notifications using AJAX, PHP, and MySQL?

I am looking to implement real-time notifications on my website and have already set up the notification bar: <div class="alert alert-info alert-with-icon" data-notify="container"> <button type="button" aria-hidden="true" class="close"> ...

What is the best way to modify the Xtype attribute based on whether the device is running on Android or iOS

I am currently working on a project using Extjs6.0.2, but I have encountered an issue with creating the xtype: 'namefield'. It seems that this type of xtype is supported on Android devices but not on iOS devices. Despite this challenge, I am dete ...

Creating a system to add and limit dynamic fields with a counter in jQuery

Check out this fiddle link http://jsfiddle.net/gKJEs/80/ I'm looking for a way to limit the number of rows that can be added, let's say up to 5. Here is the HTML code: <table id="table"></table> <button id="addRowBtn">Add Ro ...

Display Default Image in Vue.js/Nuxt.js when Image Not Found

I'm currently working on implementing a default image (placeholder image) for situations where the desired image resource is not found (404 error). I have a dictionary called article which contains a value under the key author_image. Although the stri ...

Achieving camera zoom in threeJS without the use of trackball controls or any other camera control libraries

Currently, I'm utilizing threeJS to manipulate a camera within my scene. The camera is configured to orbit in a circular motion around an object when the left and right keys are pressed on the keyboard. However, I am seeking guidance on how to impleme ...

Designate a Cookie for individual users

Currently, I am in the process of building a straightforward Wordpress website that aims to monitor a user's order using a specific Cookie. Although most of the functionalities are already implemented, an unexpected issue has surfaced. Upon logging i ...

The side navigation panel transition is stuck and failing to slide out as intended

My element is able to slide in smoothly, but encounters trouble when attempting to slide back out. I suspect the issue lies within the syntax for "display: none". Any assistance or recommendations would be greatly appreciated, and feel free to request more ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Can you explain the distinction between using call and apply?

Can you explain the distinction between utilizing Function.prototype.apply() and Function.prototype.call() to execute a function? const func = function() { alert("Hello world!"); }; func.apply() compared to func.call() Do performance dispar ...

Using the EJS if-else statement to iterate through an array of items

I am working on rendering API data using Express (REST) and EJS (template engine) based on the value of the "status" field. If any item in the array has a status other than "CLOSED," it should be displayed, but if all items have the status set to "CLOSED," ...

Error: The React styleguidist encountered a ReferenceError due to the absence of the defined

After integrating react styleguidist into my project, I encountered an issue when running npm run styleguidist. The error message states: ReferenceError: process is not defined Here is a snippet from my styleguide.config.js file: module.exports = { ti ...

What is the best way in jQuery to display a particular div with a unique id when a link is clicked?

I have a div with the following structure: <article id="#pippo">blablabla</article> which I have hidden using jQuery $('article').hide(); Now, I want to create a link menu that displays a specific article id when it's clicked ...

Here's a way to programmatically append the same icon to multiple li elements generated using document.createElement:

I am new to creating a to-do app and need some guidance. When a user enters a task, I successfully create a list item for that task. However, I am unsure how to add a delete icon next to the newly created li element. Can someone please help me out? Below ...

Connecting two sets of data from a mongoDB database using vue.js

Hey there, I'm a newcomer to vue and mongodb. I've set up two collections - one for storing user details and the other for business details. When a business registers through a form, their information is saved in mongodb. Now, I've created a ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...