2009-06-24 24 views
4

在我的表單中,我有一組用戶可以輸入值的輸入框。 更改其中一個框時,將自動提交表單。自動提交表單在x毫秒的非活動鍵盤後

現在的問題是,用戶停留在最後一個字段中,拿起鼠標並按下(另一種形式的)確定按鈕,而不必先離開文本框。更改事件不會被觸發,舊的不正確的值將傳遞到下一頁。

我想在幾個毫秒的不活動鍵盤後觸發onchange事件。就像大多數自動完成插件一樣。
我想我可以實現一個計時器,在你輸入一個輸入字段時開始計時,每次按鍵被處理時被重置,然後當它到達零時,onchange事件被觸發。

我不想重新發明輪子,並想知道這樣的功能是否可用的地方。
建議?

回答

6

我有一個類似的問題,並創建了一個當前在內部應用程序中使用的jQuery插件。它應該在用戶輸入完成後觸發更改事件。

如果你不使用jQuery,代碼仍然適用於其他任何東西。

jQuery.fn.handleKeyboardChange = function(nDelay) 
{ 
    // Utility function to test if a keyboard event should be ignored 
    function shouldIgnore(event) 
    { 
     var mapIgnoredKeys = { 
      9:true, // Tab 
      16:true, 17:true, 18:true, // Shift, Alt, Ctrl 
      37:true, 38:true, 39:true, 40:true, // Arrows 
      91:true, 92:true, 93:true // Windows keys 
     }; 
     return mapIgnoredKeys[event.which]; 
    } 

    // Utility function to fire OUR change event if the value was actually changed 
    function fireChange($element) 
    { 
     if($element.val() != jQuery.data($element[0], "valueLast")) 
     { 
      jQuery.data($element[0], "valueLast", $element.val()) 
      $element.trigger("change"); 
     } 
    } 

    // The currently running timeout, 
    // will be accessed with closures 
    var timeout = 0; 

    // Utility function to cancel a previously set timeout 
    function clearPreviousTimeout() 
    { 
     if(timeout) 
     { 
      clearTimeout(timeout); 
     } 
    } 

    return this 
    .keydown(function(event) 
    { 
     if(shouldIgnore(event)) return; 
     // User pressed a key, stop the timeout for now 
     clearPreviousTimeout(); 
     return null; 
    }) 
    .keyup(function(event) 
    { 
     if(shouldIgnore(event)) return; 
     // Start a timeout to fire our event after some time of inactivity 
     // Eventually cancel a previously running timeout 
     clearPreviousTimeout(); 
     var $self = $(this); 
     timeout = setTimeout(function(){ fireChange($self) }, nDelay); 
    }) 
    .change(function() 
    { 
     // Fire a change 
     // Use our function instead of just firing the event 
     // Because we want to check if value really changed since 
     // our previous event. 
     // This is for when the browser fires the change event 
     // though we already fired the event because of the timeout 
     fireChange($(this)); 
    }) 
    ; 
} 

用法:

$("#my_input").handleKeyboardChange(300).change(function() 
{ 
    // value has changed! 
}); 
+0

不錯。你考慮了一些情況我沒有 – 2009-06-24 09:49:39

0

我不知道這樣的解決方案將被視爲「重新發明」任何東西。正如你所說,這聽起來只不過是一個簡單的setTimeout頁面加載。大約3000毫秒後,它運行form.submit()。

我可能會重新啓動每次擊鍵的倒數計時,以使用戶有足夠的時間進行輸入。

+0

你是對的,我做到了。我只是在按鍵事件中擔心瀏覽器差異。到目前爲止沒有問題。 – 2009-06-24 09:47:02

0

它不工作做一個onBlur,所以無論是當用戶移動到下一個領域或點擊別的東西,價值被保存?

+0

當用戶單擊使用當前值轉到其他頁面的提交按鈕時,會發生該問題。在提交轉到下一頁的表單之前,沒有時間先重新提交以前的表單。 – 2009-06-24 09:45:10