[英]Regex not working in jquery for form validation
我正在運行以下jquery腳本:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#textThing").blur(function(){
var isNumber = $("#textThing").val().match(/^\d+/);
$("#p2").html(isNumber);
});
});
</script>
</head>
<body>
<input type="text" id="textThing" />
<p id="p2">Paragraph 2</p>
</body>
</html>
問題是,當我取消選擇輸入時,p2不會給我任何東西。 我做錯了什么?
您需要說:
$("#p2").html(isNumber == null ? "" : isNumber[0]);
代替:
$("#p2").html(isNumber);
...因為.match()
如果匹配則返回一個數組。 參見此處: https : //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/match
這是一個工作版本: http : //jsfiddle.net/k45Ka/5/
工作演示 http://jsfiddle.net/r4VPZ/3/ 或 http://jsfiddle.net/r4VPZ/4/
您可以在上方看到.match
解釋。
您還可以將.toString
與.html
或.text
api結合使用。 您可以進行null
處理,也可以查看isNaN
http://www.w3schools.com/jsref/jsref_isnan.asp
希望對您有所幫助,如果我錯過了任何事情,請告訴我,干杯:)
好的閱讀: http : //api.jquery.com/html/ 和 http://api.jquery.com/text/
Match
: .match
返回什么: 學習正則表達式和jquery-.match返回什么?
碼
$(document).ready(function(){
$("#textThing").on("blur",function(){
var isNumber = $("#textThing").val().match(/^\d+/);
$("#p2").html(isNumber.toString());
// $("#p2").text(isNumber);
});
});
//var folioIsNumResult = $("#Folio").val().match(/^\d+/i);
演示: http : //jsfiddle.net/epinapala/TbCfc/
當不匹配正則表達式時,match返回null!
$(document).ready(function(){
$("#textThing").blur(function(){
var isNumber = $(this).val().match(/^\d+/);
if(isNumber == null){
var res = "not a number"
}else{
var res = "valid number";
}
$("#p2").html(res);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.