2017-05-24 40 views
-2

我的要求非常明確,我不希望字母在我的文本字段中,但不能將文本字段更改爲數字。通過使用以下jQuery我已經實現了,但問題是我不能在文本字段中分配ID。 因爲在我實際的代碼我沒有ID,因此不能使用 $(「#T2」)。在(「的keydown KEYUP」,函數(E)該代碼。 有沒有其他的替代調用。在不知道文本字段ID的情況下調用jquery函數

繼代碼工作,但不能在現實

<!doctype html> 
    <head> 

    <script 
     src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script> 
    $(function() { 
    var regExp = /[a-z]/i; 
    $('#t2').on('keydown keyup', function(e) { 
var value = String.fromCharCode(e.which) || e.key; 

    // No letters 
    if (regExp.test(value)) { 
    e.preventDefault(); 
    alert("only nos allowed"); 
    return false; 
    } 
    }); 
    }); 
     </script> 

    <body> 
     <form> 
     <input type="text" name="t1" id="t2"> 
    </form> 
    </body> 
    </html> 
+0

'的問題是,我不能在文本field'分配ID ...但你的文本字段中確實有一個ID,不是嗎? 'id =「t2」' –

+0

$(「input」)。on ... –

+0

您的輸入有一個ID ..無論類型。類型不支配元素屬性 – ThisGuyHasTwoThumbs

回答

0

嘗試給ID使用你的文本框這樣

 <input type="text" name="t1" id="t2" onkeydown="textchange(event)" keyup="textchange(event)" > 
function textchange(e){ 
    var value = String.fromCharCode(e.which) || e.key; 
    // No letters 
    if (regExp.test(value)) { 
    e.preventDefault(); 
    alert("only nos allowed"); 
    return false; 
    } 
    }); 
} 
+0

這不工作 –

+0

你可以得到哪個錯誤? – Jay

0

您可以使用$(":input")選擇所有輸入元素,或給你的輸入欄常見的類名,然後使用$(".classname")選擇器。

有關詳細的選擇,你應該檢查this

+0

但我如何使用兩個選擇器輸入和類名 –

+0

您不必使用展位。只要選擇一個最適合的。但是如果你想結合這些,解決方案將是'$(「。classname:input」)' – Anrijs

相關問題