用戶完成鍵入而不是按鍵盤鍵時運行javascript函數?

我想在用戶完成在文本框中的輸入後觸發ajax請求。 我不但願它在用戶每次輸入字母時都運行該函數,由於這會致使不少ajax請求,可是我也不但願他們也必須按下Enter鍵。 html

有沒有一種方法可讓我檢測用戶什麼時候完成鍵入,而後再執行ajax請求? ajax

在這裏使用jQuery! 戴夫 json


#1樓

若是您要查找特定長度(例如郵政編碼字段): 服務器

$("input").live("keyup", function( event ){
if(this.value.length == this.getAttribute('maxlength')) {
        //make ajax request here after.
    }
  });

#2樓

var timer;
var timeout = 1000;

$('#in').keyup(function(){
    clearTimeout(timer);
    if ($('#in').val) {
        timer = setTimeout(function(){
            //do stuff here e.g ajax call etc....
             var v = $("#in").val();
             $("#out").html(v);
        }, timeout);
    }
});

此處的完整示例: http : //jsfiddle.net/ZYXp4/8/ 函數


#3樓

不知道個人需求是否有點奇怪,可是我須要與此相似的東西,這就是我最終使用的東西: post

$('input.update').bind('sync', function() {
    clearTimeout($(this).data('timer'));            
    $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
        if(x.success != true) {
            triggerError(x.message);    
        }
    }, 'json');
}).keyup(function() {
    clearTimeout($(this).data('timer'));
    var val = $.trim($(this).val());
    if(val) {
        var $this = $(this);
        var timer = setTimeout(function() {
            $this.trigger('sync');
        }, 2000);
        $(this).data('timer', timer);
    }
}).blur(function() {
    clearTimeout($(this).data('timer'));     
    $(this).trigger('sync');
});

這使我能夠在應用程序中包含如下元素: this

<input type="text" data-url="/controller/action/" class="update">

當用戶「完成鍵入」(2秒鐘不執行任何操做)或轉到另外一個字段(元素模糊)時,哪一個更新 編碼


#4樓

這是一個與underscore.js防抖動功能只有一條線路url

$('#my-input-box').keyup(_.debounce(doSomething , 500));

這基本上是說我中止輸入500毫秒後的doSomethingspa

有關更多信息: http : //underscorejs.org/#debounce


#5樓

我正在列表中實施搜索,所以須要基於Ajax的搜索。 這意味着在每次關鍵更改時,應更新並顯示搜索結果。 這致使發送到服務器的ajax調用太多,這不是一件好事。

通過一些工做後,我採起了一種在用戶中止鍵入時ping服務器的方法。

此解決方案爲我工做:

$(document).ready(function() {
    $('#yourtextfield').keyup(function() {
        s = $('#yourtextfield').val();
        setTimeout(function() { 
            if($('#yourtextfield').val() == s){ // Check the value searched is the latest one or not. This will help in making the ajax call work when client stops writing.
                $.ajax({
                    type: "POST",
                    url: "yoururl",
                    data: 'search=' + s,
                    cache: false,
                    beforeSend: function() {
                       // loading image
                    },
                    success: function(data) {
                        // Your response will come here
                    }
                })
            }
        }, 1000); // 1 sec delay to check.
    }); // End of  keyup function
}); // End of document.ready

您會注意到,在實現此功能時無需使用任何計時器。

相關文章
相關標籤/搜索