簡體   English   中英

如何允許除數字以外的所有字符?

[英]How to allow all the characters except numbers?

我想允許除數字以外的所有字符。 我寫下面的jQuery。

$(".no-numbers").keypress(function(e){
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
  {
    swal({
    title: "",
    text: "Numbers are not allowed"
    });

    return false;
  }
  else
  {
    return true;
  }
}); 

上面的代碼不接受任何內容...請幫助!!!

請嘗試以下操作:

$(".no-numbers").keypress(function(e){
  var key = e.keyCode;
  if (key >= 48 && key <= 57) {
    swal({
    title: "",
    text: "Numbers are not allowed"
    });

    return false;
  }
  else
  {
    return true;
  }
}); 

或者您可以使用如下正則表達式:

var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
  // do your stuff here
}

參考如何找出按下了哪個字符鍵? ;

您可以將按鍵轉換為實際值,然后使用e.preventDefault()忽略輸入。

 $(".no-numbers").keypress(function(e) { var numbers = ['0','1','2','3','4','5','6','7','8','9']; var keynum; if (window.event) { // IE keynum = e.keyCode; } else if (e.which) { // Netscape/Firefox/Opera keynum = e.which; } if (numbers.indexOf(String.fromCharCode(keynum)) > -1) { alert("No numbers please."); e.preventDefault(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class="no-numbers"> 

看起來您的if陳述有誤

看看這個沙箱https://codesandbox.io/s/91wrqorl7o

if (e.which >= 48 && e.which <= 57) {
  console.log("Not accepted is a  Numbers");
  return false;
} else {
  console.log("Accepted not a number");
  return true;
}

你的條件是錯誤的。

您必須測試48至57的鍵碼。還要測試96至105的鍵區號。

您的原始情況說明:

(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 

如果密鑰不是退格鍵(8)

如果鍵不是...鍵碼為零!!

如果鍵在鍵碼48以下在鍵碼57以下->這與您想要的相反!


現在看下面的代碼片段;)

 $(".no-numbers").keydown(function(e){ if ( (e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105) ){ swal({ title: "", text: "Numbers are not allowed" }); return false; } else { return true; } }); 
 <link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.28.5/sweetalert2.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.28.5/sweetalert2.min.js"></script> <input class="no-numbers"> 

旁注...我總是傾向於使用會先觸發的keydown事件來測試和“防止”鍵盤按下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM