2012-03-02 45 views
0

我想一個文本框的最大長度設置爲7,並停止進一步的鑰匙進入和使用的preventDefault但它給錯誤 我的代碼如下的preventDefault()不工作給予對象不支持此屬性

function crInputRK(ctrlid, ControlValue, size, clsName)         { 

    var newTextBox = crE('input'); 
    newTextBox.type = 'text'; 
    newTextBox.style.fontSize = ".9em"; 
    newTextBox.style['width'] = size; 
    newTextBox.style['height'] = '12px'; 
    newTextBox.style['float'] = 'none'; 
    newTextBox.style['margin'] = '0 0 0 10px';//added on 13feb2012 
    //newTextBox.maxLength = '3'; 
    newTextBox.id = ctrlid; 

    newTextBox.className = 'inputDate'; 

    //newTextBox.onchange = "javascript:return EnableButton();"; 

    //ControlValue = getControlValue(ctrlid); 
    if (ControlValue != "") 
     newTextBox.value = ControlValue; 
    if (ControlValue == "Multiple") 
     newTextBox.disabled = true; 
     newTextBox.setAttribute("onkeypress", "javascript:SetMaxLength(event,this);"); 


    return newTextBox; 
} 


function SetMaxLength(e, txtbox)               { 

    var MaxLength = 7; 
    if (_$(txtbox.id).value.length >= MaxLength) { 
     e.preventDefault(); 

    } 
} 
+0

什麼是你的jQuery的版本? – Raptor 2012-03-02 09:04:32

+0

這是你的瀏覽器? – Diode 2012-03-02 10:20:40

+0

版本1.4.1.js – JainNavneet 2012-03-02 15:00:25

回答

0

只是一種選擇:要求需要的範圍之內進行評估擊鍵監控

 

var MaxLength = 7; 
if (_$(txtbox.id).value.length >= MaxLength) { 
    _$(txtbox.id).value = _$(txtbox.id).value.substring(0, MaxLength); 
} 
 
+0

感謝sudhir其作品..... @ jain – JainNavneet 2012-03-02 16:12:17

0

輸入欄「上的」(jQuery的1.7+)或「活的」(jQuery的1.4.2-1.7)。如果不這樣做,輸入字段將僅在頁面加載時進行評估。所以,你需要監視輸入做這樣的事情......

function SetMaxLength(e,txtbox){ 
    var MaxLength = 7; 
    $("#"+_$(txtbox.id)).live('keyup', function(e){ 
    if (_$(txtbox.id).value.length >= MaxLength) { 
     e.preventDefault(); 
    } 
    }); 
} 

這將監測你的領域的所有行動,如果長度比的MaxLength大於它不會執行默認操作。

0

event.preventDefault是不是跨瀏覽器兼容的,如果你需要支持舊版本的Internet Explorer,請嘗試使用事件,而不是(假設你有jQuery的可用):

jQuery(newTextBox).bind('keypress', SetMaxLength); 

SetMaxLength功能將在隨後的運行範圍文本框而不是讓它作爲參數傳遞:

function SetMaxLength(e, txtbox) { 
    var MaxLength = 7; 
    if (this.value.length >= MaxLength) { 
    return false; // or e.preventDefault(); 
    } 
} 
0

可以使用.preventDefault();

$("body").find("input[type=text]").each(function(k,v) { 
    $(this).on('keypress', function(event) { 
     limit = 7; //for example 
     val = $(this).val(); 
     len = val.length; 
     if(len > limit-1) { event.preventDefault(); } 
      }); 
    }); 

Demo

相關問題