2011-08-23 28 views
1

因此,我對jquery完全陌生,並試圖找出如何將我的功能應用於多個文本框,我最終需要將它連接到另一個類似於一個我有,但我無法弄清楚如何勾住他們,所以他們不允許某些輸入。任何意見都非常感謝。麻煩將我的功能應用於多個文本框

<html> 
<head> 


<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 

$(document).ready(function(){ 


$("#textBox").keypress(function (e) //the function will check the textbox 
{ 


    if(e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) 
    { 
    return false; 
    } 
}); 





}); 
</script> 

</script> 

</head> 
<body> 

<font face='courier'> 
Numbers Only : <input type="text" id="textBox" /><br/> 
Letters Only : <input type="text" id="textBox2" /> 

</body> 
</html> 

由於提前,

+0

你想要什麼?你的'keypress'功能適用於兩個文本框?或者每個文本框有不同的'keypress'功能?無論如何,我認爲查看jQuery選擇器文檔可能會非常有幫助:http://api.jquery.com/category/selectors/ –

+0

請注意,您關閉了腳本標記兩次,但未關閉字體標記。 – Stefan

+0

Stefan,在發佈這段感謝之後不久我就發現了我的不匹配標籤,James是我最終想要連接一個非常類似的函數,它只允許以與第一個文本框限制輸入的數字相同的方式輸入字母。 – John

回答

4

嘗試該

$("#textBox,#textBox2").keypress(); 

所提供的示例僅選擇一個文本區域。您正在使用僅使用一次的特定ID。

http://api.jquery.com/multiple-selector/

+1

謝謝,我仍然只是習慣jQuery語法,但工作得很好 – John

2

只需使用一類選擇,或屬性選擇:

$('input[type="text"]').keypress(function(e) { 
    // ... 
}); 
2

使用類屬性:

<input type="text" class="myclass" id="textBox" /> 
<input type="text" class="myclass" id="textBox2" /> 

在JavaScript

$(".myclass").keypress(function (e) //the function will check the textbox 
2

到功能適用於所有input type="text"元素:

變化:

$("#textBox").keypress(function (e) //the function will check the textbox 

要:

$(":text").keypress(function (e) //the function will check the textbox 

如果你只希望它適用於某些文本輸入框,標籤與輸入class =「myClass」並將jquery行更改爲:

$(".myclass").keypress(function (e) //the function will check the textbox 
1

寫你的所有文本框相匹配的選擇或使用多重選擇器。

http://api.jquery.com/multiple-selector/

我建議你添加一個CSS類,你想選擇的所有元素。這使得未來添加更多元素變得更加容易。

1

你可以簡單地通過使用CSS樣式逗號應用現有的功能,以這兩個框:

$("#textBox, #textBox2").keypress(function (e) 

這個(顯然)防止信件在這兩個盒子。