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


当前回答

简单的方法:

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

其他回答

对我来说,解决方案是:

<input type=“number” min=“0” oninput=“this.value = Math.abs(this.value)”>

Edit

正如注释中所建议的那样,如果0是最小值,则需要进行微小的更改。

<输入类型=“数字” min=“0” oninput=“this.value= !!this.value && Math.abs(this.value) >= 0 ?Math.abs(this.value) : null“>

仅供参考:使用jQuery,你可以用以下代码覆盖focusout上的负值:

$(document).ready(function(){
    $("body").delegate('#myInputNumber', 'focusout', function(){
        if($(this).val() < 0){
            $(this).val('0');
        }
    });
});

这并不能取代服务器端验证!

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

如果你不想在HTML中添加更多代码,只需要添加另一种方法(使用Angular):

您只需要订阅字段valueChanges并将Value设置为绝对值(注意不要触发新事件,因为这会导致另一个valueChange,因此会触发递归调用并触发最大调用大小超出错误)

HTML代码

<form [formGroup]="myForm">
    <input type="number" formControlName="myInput"/>
</form>

TypeScript代码(在组件内部)

formGroup: FormGroup;

ngOnInit() { 
    this.myInput.valueChanges 
    .subscribe(() => {
        this.myInput.setValue(Math.abs(this.myInput.value), {emitEvent: false});
    });
}

get myInput(): AbstractControl {
    return this.myForm.controls['myInput'];
}
oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"