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


当前回答

我想允许小数,如果输入负数,不清除整个输入。这在铬至少工作良好:

<input type="number" min="0" onkeypress="return event.charCode != 45">

其他回答

@Manwal的回答很好,但我喜欢少写几行代码的代码,这样可读性更好。另外,我喜欢在html中使用onclick/onkeypress的用法。

我建议的解决方案也是如此: 添加

min="0" onkeypress="return isNumberKey(event)"

到HTML输入和

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

作为一个javascript函数。

如前所述,它做的是一样的。这只是个人对如何解决问题的偏好。

这个问题的答案是没有帮助的。因为它只在你使用上/下键时起作用,但如果你输入-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

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

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