如何从js中的文本字段中获取整数?

问题描述

所以我只想从 html 输入中获取整数并在 js 中使用它。

function apply(){
    let input = document.getElementById("txtfield").value;
    console.log(input);
    document.getElementById("txtfield").value = '';
}
<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>stack qustion</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <input id="txtfield">
  <button onclick="apply()" id="apply">apply</button>                              
    <script src="script.js"></script>
</body>
</html>

解决方法

您可以将 type="number" 添加到您的输入字段,以便用户只能输入数字:

<input type="number" id="txtfield">

或者,如果您只想获取整数并仍然能够将其他字符输入到文本字段中。然后你必须为你的函数添加一个检查。此正则表达式 input.replace(/\D/g,'') 将从输入字符串中删除所有非数字字符:

function apply(){
    let input = document.getElementById("txtfield").value;
    console.log(input.replace(/\D/g,''));
    document.getElementById("txtfield").value = '';
}
<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>stack qustion</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <input id="txtfield">
  <button onclick="apply()" id="apply">apply</button>                              
    <script src="script.js"></script>
</body>
</html>

,

使用 regex 替换所有非数字值:

function apply(){
    let input = document.getElementById("txtfield").value;
    console.log(input.replace(/[^0-9\.]+/g,''));
    document.getElementById("txtfield").value = '';
}
<!DOCTYPE html>
<html lang="en">
<head>
    
    <title>stack qustion</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
  <input id="txtfield">
  <button onclick="apply()" id="apply">apply</button>                              
    <script src="script.js"></script>
</body>
</html>