最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax call on textarea change, but not on every change - Stack Overflow

programmeradmin0浏览0评论

I'm making a kind of note system for my users in Laravel application. I want this textarea that the user writes their notes on to be saved after the user is done typing, instead of running the ajax call on every change done because that would be a lot of requests.

What is the best way to achieve this? Should I use some sort of timer here to determine if the user is done writing?

Currently I'm just using the following:

notesTextarea.on('change', function(e) {
   $.ajax({ ... });
});

I'm making a kind of note system for my users in Laravel application. I want this textarea that the user writes their notes on to be saved after the user is done typing, instead of running the ajax call on every change done because that would be a lot of requests.

What is the best way to achieve this? Should I use some sort of timer here to determine if the user is done writing?

Currently I'm just using the following:

notesTextarea.on('change', function(e) {
   $.ajax({ ... });
});
Share Improve this question edited Oct 19, 2019 at 13:07 Mamun 69k9 gold badges51 silver badges62 bronze badges asked Oct 19, 2019 at 11:57 KaizokupuffballKaizokupuffball 2,8438 gold badges43 silver badges64 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

While the other proposed solutions (on blur or on keydown if it's the enter key), would work, I think they're not what you're looking for.

What if the user neither clicks outside the textarea, nor uses enter? I would use a technique called debounce instead. You can read about it for example here: https://davidwalsh.name/javascript-debounce-function or see an example here: https://www.geeksforgeeks/debouncing-in-javascript/

The short version is, it only calls a function after an event has stopped firing for a given length of time.

Add the debounce function to your code by either using an NPM package (ex. https://www.npmjs./package/debounce) or directly adding the necessary code:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, 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);
    };
};

Source: https://davidwalsh.name/javascript-debounce-function which has taken it from Underscore.js

Then have a function doing your ajax calls like:

var makeAjaxCall = function(e) {
    $.ajax({ ... });
};

Now you can simply add a listener like:

var minTimeoutBetweenCallsInMilliSeconds = 500;
notesTextarea.on('change', debounce(makeAjaxCall, minTimeoutBetweenCallsInMilliSeconds));

Now the makeAjaxCall function would be called only 500ms after the last change event occurred, a.k.a. the user stopped typing.

You can use the onlbur event instead. It happens when the element lost the focus, that could means you are no longer changing its content:

$("#notesTextarea").on('blur', function(e) {
     // $.ajax({ ... });
     console.log("has finished, content to be saved:" + $(this).val());
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Notes: <textarea id="notesTextarea"></textarea>
</p>
<p>
Other something: <input type="text">
</p>

One way, you can make the call on pressing the enter key on keydown event:

notesTextarea.on('keydown', function(e) {
  if(e.keyCode == 13){
    $.ajax({ ... });
  }
});

You can also think of blur which will occur when the element loses focus

notesTextarea.on('blur', function(e) {
  $.ajax({ ... }); 
});

If you want to automate this saving you can call to ajax, after N number of characters typed by user each time.

Otherwise, you can call to ajax function on CTRL+S key bination

document.addEventListener('keydown', function(event) {

if (event.ctrlKey && event.key == 's') {
event.preventDefault();  //prevent default file save box open by browser
  alert('ajax call goes here!');


}

});

Similar to @Mamun's answer.

Call Ajax on keypress event:

$("textarea").on('keypress', function() {
    //$.ajax({ ... });
    console.log('request sent!');
});
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<textarea id="textarea"></textarea>
</p>

发布评论

评论列表(0)

  1. 暂无评论