2012-12-10 72 views
1

我正在查找一個腳本,它在達到文本字段的最大長度時自動調用JavaScript函數。在文本字段的最大長度上調用javascript函數

我試圖修改此一段腳本,我發現這裏ajax call after x characters

$("input#zipcode").live("keyup", function(event){ 
    if(this.value.length == this.getAttribute('maxlength')) { 
     if(!$(this).data('triggered')) { 
      // set the 'triggered' data attribute to true 
      $(this).data('triggered',true); 
      if ($(this).valid() == true) { loadXMLDoc(); } 
     } 
    } else { $(this).data('triggered',false); } 
}); 

這是代碼包含loadXMLDoc部分的部分:

function loadXMLDoc() 
{ 
var xmlhttp; 
if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    {// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4) 
    { 
    document.getElementById("state_insert").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","state_insert.asp?zipcode="+document.getElementById('zipcode').value,true); 
xmlhttp.send(); 
} 

當達到最大長度,我想它要求一個「LoadXMLDoc」函數,它不需要傳遞額外的參數。

目前我有它設置爲的onblur = 「loadXMLDoc()把」 像這樣:

[input name='zipcode' type='text' class="form_elements" id='zipcode' tabindex='11' autocomplete='off' onchange="this.value=extractNumeric(this.value)" onkeypress="return isNumericKey(event)" value='' size="4" maxlength="5" onblur="loadXMLDoc()" /]

我使用的[和]因爲<和>是不允許的。

在文本字段屬性中,但我希望在輸入郵政編碼的5位數字後立即加載。

感謝提前:)

Robert. 
+0

代碼似乎是一個不尋常的東西組合...如果你使用jQuery爲什麼不完全使用它? – elclanrs

+0

你有我應該怎麼做的例子嗎?我對JavaScript沒有經驗。 –

+0

在我的測試中,它似乎應該工作......但我在JavaScript控制檯中發現一個錯誤,指出'.valid()'不是函數。 – jwatts1980

回答

0

你可以用onkeypress事件事件做到這一點,如:

onkeypress="return isNumericKey(event,this)" 

它也應該檢查最大長度的號碼。代碼應該是這樣的:

function isNumericKey(evt,zip) { 
    // your Number 
    // check here 

    var zipLen=zip.getAttribute('maxlength'); 
    var zipValueLen=zip.value.length; 
    if(zipValueLen>=zipLen) { LoadXMLDoc(); return false;} 
}