Is there any way to prevent input type=“number” ge

2019-01-10 01:26发布

I want to get only positive values, is there any way to prevent it using only html
Please don't suggest validation method

Screenshot of input control

13条回答
冷血范
2楼-- · 2019-01-10 02:00
oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"
查看更多
甜甜的少女心
3楼-- · 2019-01-10 02:01

For me the solution was:

<input type="number" min="0" oninput="this.value = Math.abs(this.value)">
查看更多
干净又极端
4楼-- · 2019-01-10 02:03

The @Manwal answer is good, but i like code with less lines of code for better readability. Also i like to use onclick/onkeypress usage in html instead.

My suggested solution does the same: Add

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

to the html input and

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

as a javascript function.

As said, it does the same. It's just personal preference on how to solve the problem.

查看更多
甜甜的少女心
5楼-- · 2019-01-10 02:08

Just for reference: with jQuery you can overwrite negative values on focusout with the following code:

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

This does not replace server side validation!

查看更多
男人必须洒脱
6楼-- · 2019-01-10 02:12

I wanted to allow decimal numbers and not clear the entire input if a negative was inputted. This works well in chrome at least:

<input type="number" min="0" onkeypress="return event.charCode != 45">
查看更多
Fickle 薄情
7楼-- · 2019-01-10 02:13

Use the min attribute like this:

<input type="number" min="0">
查看更多
登录 后发表回答