2017-05-28 47 views
-1

我的代碼爲form禁用HTML文本框中的鍵

<tr> 
      <td>Nombre:</td> 
      <td><input type="text" name="company" autofocus id="company"/></td> 
</tr> 

所以想在這個輸入中禁用一些鍵作爲V,C,任何鍵。

這可能嗎?

+0

是。這是可能的。 – AdhershMNair

+0

讓我知道,更安全的方法來做到這一點;一個例子? – c3media

+2

[禁用輸入字段中的某些字符]的可能重複(https://stackoverflow.com/questions/14806200/disable-some-characters-from-input-field) –

回答

0

你可以聽​​事件,並防止input如果你的關鍵是被禁止的:

const i = document.getElementById('company'); 
 

 
i.addEventListener('keydown', function(e) { 
 
    if (['C', 'V'].includes(e.key)) { 
 
    e.preventDefault(); 
 
    } 
 
})
<input type="text" name="company" autofocus id="company"/>

0

這僅僅是一個示例代碼,以防止這些密鑰。你可以使用它的需要。

document.onkeydown = function(e) { 
     if (e.keyCode === 67||e.keyCode === 86) { //C, V will be disabled. 
      e.preventDefault(); 
      alert('not allowed'); 
     } 
     return false; 
} 
0

當您使用HTML5,你可以使用pattern屬性 這包含了你想要的規則正則表達式。

我的例子不使用JavaScript,但也可以解決你的問題

像這個例子:

<form action="/action_page.php"> 
    Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code"> 
    <input type="submit"> 
</form> 

這將只接受三個字母的國家代碼