在 JavaScript 中检查输入是数字还是字母?

javascriptweb developmentobject oriented programming更新于 2025/11/10 22:04:17

要检查输入是数字还是字母,请使用 JavaScript 中的 isNaN() 函数。如果值为 NaN(即不是数字),则返回 true。以下是代码 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.
css" integrity="sha384- BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
</head>
<body>
<form name="checkingInput" action="" onsubmit="return
checkInputIsNumber()">
Enter the value: <input type="text" name="txtValue">
<br>
<input type="submit" value="check">
<script>
   function checkInputIsNumber(){
      var value=document.forms["checkingInput"]["txtValue"].value;
      if (isNaN(value)){
         alert("Please Provide the input as a number");
         return false;
      }
   }
</script>
</body>
</html>

要运行上述程序,请将文件名保存为"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。

输出

将产生以下输出 −

如果您提供除数字以外的任何值,您将收到一条警报消息。这将产生以下输出 −

在这里,我输入值 100。屏幕截图如下 −

单击检查按钮后,您将获得查询字符串形式的值,例如 −

?txtValue=yourValue.

这将产生以下输出 −


相关文章


有用资源