以下範例示範如何在表單中判斷使用者輸入的內容是否為數字。
程式碼如下:
<html xmlns="https://www.3lian.com/">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js判斷輸入是否為數字</title>
<script language="javascript">
function ischeckNum()
{
var num = document.getElementById('isnum').value;
if( num )
{
if( !isNaN( num ) )
{
alert('是數字');
return false;
}
else
{
alert('你輸入的數據不是數字');
myfm.isnum.select();
return false;
}
}
else
{
alert('需輸入內容');
myfm.isnum.focus();
}
}
</script>
</head>
<body>
<form name="myfm" method="post" action="">
<label>
<input type="text" name="isnum" id="isnum">
</label>
<label>
<input type="button" name="Submit" value="檢測是否為數字" onClick="ischeckNum();">
</label>
</form>
</body>
</html>
說明:在 JavaScript 中要判斷使用者輸入的內容是否為數字,只要用 isNaN 判斷一下就可以了。
isNaN(numValue) 中,numValue 是必選參數,代表要檢查是否為 NaN 的值。如果該值是 NaN,則 isNaN 函式會回傳 true,否則回傳 false。
使用這個函式的典型情況,是檢查 parseInt 與 parseFloat 方法的回傳值。此外還有一種判斷方式:讓變數與它自身進行比較,如果比較結果不相等,那麼它就是 NaN——因為 NaN 是唯一與自身不相等的值。