【问题标题】:Jquery input text allow decimal and value between 0.00 and 100Jquery 输入文本允许小数和 0.00 到 100 之间的值
【发布时间】:2017-03-28 15:00:05
【问题描述】:

jQuery 输入文本允许小数和 0.00 到 100 之间的值

HTML:

<input name="score type="number" min="0.01" max="100" step="0.01">

当我输入“1111”时显示无效,但我想在点击提交按钮后进行验证

<input type="text" name="score">
<input type="submit">

脚本:

if($(this).val()<= 0.01 && ($(this).val() <=100)){ // allow 0.01 to 100 100
     return true;
}

我想在字段中只允许小数

【问题讨论】:

  • 这里有问题吗?
  • 你的答案是。使用 html5 而不是 javascript 来查看@Marijn 的答案
  • 当我更改该字段的值时,input type="number" 无法正常工作
  • @Developer:您是如何更改该字段的值的? “无法正常工作”是什么意思?
  • 您希望在用户提交信息(点击按钮)或用户输入文本(按键)时进行检查?

标签: javascript jquery input range decimal


【解决方案1】:

您可以为此使用 HTML:

&lt;input type="number" min="0" max="100" step="0.01"&gt;

如果您不想使用 HTML:

$(document).on("ready", function() {
  
  $("#form").submit(function(e) {

    var scoreVal = $("#score").val();
    
    if(parseInt(scoreVal) <= 0 || parseInt(scoreVal) > 100) {
      
      e.preventDefault();
      
      console.log("Wrong value was entered!");
    
    }
    
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <input id="score" type="text" name="score">
  <input type="submit">
</form>

【讨论】:

  • @Martijn input type="number" 在我更改该字段的值时无法正常工作。那是我正在尝试为 type="text" 字段实现脚本
  • @MilindAnantwar,它将勾勒出红色框(至少在 FireFox 中),并在超出规范时阻止提交。
  • @MilindAnantwar 你是什么意思?用户不能在 type="number' 字段中输入除数字以外的任何内容
  • @Logar: 用户可以输入数字 > 100
  • @Milind: true,但可以使用:out-of-range(或:invalid)伪类根据超出范围或其他无效的值设置元素样式.
【解决方案2】:

@Martijn Bots 解决方案对我来说似乎很公平,如果您想这样做,那么您可以专门检查 0.00,然后更正您的逻辑以验证范围 >=0.01 到 100

function validate()
{
   if ( jQuery("#mytext").val() == "0.00"
   || ( $("#mytext").val() >= 0.01 && $("#mytext").val() <=100)  
   )
      { 
     alert(true);
     }
    else {
      alert(false);
     }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="mytext" type="text" name="score" onblur="return validate();">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    • 2021-12-13
    相关资源
    最近更新 更多