【问题标题】:How to get just integers out of a textfield in js?如何从js中的文本字段中获取整数?
【发布时间】:2021-04-15 11:17:57
【问题描述】:

所以我想从 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>

【问题讨论】:

    标签: javascript html input textfield


    【解决方案1】:

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

    &lt;input type="number" id="txtfield"&gt;

    或者,如果您只想取出整数并且仍然能够在文本字段中输入其他字符。然后你必须在你的函数中添加一个检查。这个正则表达式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>

    【讨论】:

    • wfewfwe44d 错误
    • 我已经更新了正则表达式。这个应该适用于wfewfwe44d
    【解决方案2】:

    使用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>

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2012-12-19
      • 1970-01-01
      • 2021-08-17
      • 2017-04-06
      • 2021-10-06
      • 1970-01-01
      相关资源
      最近更新 更多