我想只得到正的值,有什么方法来防止它只使用html 请不要建议验证方法


当前回答

这个问题的答案是没有帮助的。因为它只在你使用上/下键时起作用,但如果你输入-11,它就不起作用。这是我用的一个小方法

这个是整数

  $(".integer").live("keypress keyup", function (event) {
    //    console.log('int = '+$(this).val());
    $(this).val($(this).val().replace(/[^\d].+/, ""));
    if (event.which != 8 && (event.which < 48 || event.which > 57))
    {
        event.preventDefault();
    }
   });

当你有价格的时候

        $(".numeric, .price").live("keypress keyup", function (event) {
     //    console.log('numeric = '+$(this).val());
    $(this).val($(this).val().replace(/[^0-9\,\.]/g, ''));

    if (event.which != 8 && (event.which != 44 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
   });

其他回答

如果数字是负数或正使用ES6的数学。标志 Const num = -8; // Old Way Num === 0 ?Num: (Num > 0 ?1: -1);/ / 1 // ES6方式 Math.sign (num);/ / 1

这个解决方案允许所有键盘功能,包括复制粘贴键盘。它可以防止用鼠标粘贴负数。它适用于所有浏览器,代码依赖的演示使用了bootstrap和jQuery。这应该适用于非英语语言设置和键盘。如果浏览器不支持粘贴事件捕获(IE),它将在焦点消失后删除负号。这个解决方案的行为与本机浏览器的min=0 type=number一样。

标记:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

Javascript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

这个代码对我来说工作得很好。你能查一下吗:

<input type="number" name="test" min="0" oninput="validity.valid||(value='');">

< input type = "数量" name = " credit_days "模式= ^ \[-]+” # credit_days = " ngModel " class = "表单控件” 占位符="{{'输入信用天数' |翻译}}" min="0" [(ngModel)] = " provider.credit_days " onkeypress = "返回(事件。charCode == 8 ||事件。charCode == 0 || 事件。charCode == 13) ?Null:事件。charCode >= 48 &&事件。charCode < = 57" onpaste="return false"> .

简单的方法:

<input min='0' type=“number” onkeypress=“return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57”>