nir
nir

Reputation:

text input keyup event with time interval

I have a textbox. I want to call a ajax callback function with some 2 second delay on every keyup.

How to implement this?

Upvotes: 0

Views: 4516

Answers (5)

nuit
nuit

Reputation: 29

Using jQuery, but feel free to substitute your own JS library of choice:

var currentTimer = null;
var post_id = null

$("#id_title").on('input', function (e) {

    if (!currentTimer) {
        currentTimer = true;
        setTimeout(function() {
            if (currentTimer) {
                currentTimer = null;

                // Do ajax call here
                $.post('{% url "save_post_ajax" %}', {
                    post_id: post_id,
                    title: $('#id_title').val(),
                    body: e.target.innerHTML,
                    csrfmiddlewaretoken: csrftoken
                }, function(data) {
                    if (data['status'] == 'ok') {
                        console.log(data['post_id'])
                        post_id = data['post_id']
                    }
                })
                console.log('sended')
            }
        }, 2000);
    }

})

This works better than keyup because on press alt or changing window could not send ajax. onInput is way to prevent it.

Upvotes: 0

Fantastic.4
Fantastic.4

Reputation:

2 second after last key press or every key press?

<input type="text" id="txtBox" value="" width="200px"/>
<input type="text" id="txt" width="200px"/>

<script type="text/javascript">
    $(document).ready(function(){
    $("#txtBox").keyup(function(){
        setTimeout(function(){
            $("#txt").val($("#txtBox").val());//Here call ajax code
        },2000);
      });
    });
</script>

Upvotes: 1

Philippe Leybaert
Philippe Leybaert

Reputation: 171914

If you're using jQuery, you can use the excellent delayedObserver plugin.

Upvotes: 0

RaYell
RaYell

Reputation: 70494

I'm using jQuery here but you should get the point:

function callAjax() {
    timer = null;

    // handle all your ajax here
}

var timer = null;

$('input').keyup(function () {
    // this will prevent you from reseting the timer if another key is pressed
    if (timer === null) {
        timer = setTimeout(callAjax, 2000);
    }
});

Upvotes: 0

Augustus
Augustus

Reputation: 294

Using jQuery, but feel free to substitute your own JS library of choice:

var currentTimer = null;
input.bind('keyup', function () {
    if (!currentTimer) {
        currentTimer = true;
        setTimeout(function() {
            if (currentTimer) {
                currentTimer = null;

                // Do ajax call here
            }
        }, 2000);
    }
});

Upvotes: 0

Related Questions