簡體   English   中英

有什么辦法可以防止 input type="number" 得到負值嗎?

[英]Is there any way to prevent input type="number" getting negative values?

我只想獲得正值,有什么辦法可以防止它只使用 html
請不要建議驗證方法

輸入控件截圖

像這樣使用min屬性

<input type="number" min="0">

我對@Abhrabm 的回答不滿意,因為:

它只是防止負數從向上/向下箭頭被輸入,而用戶可以從鍵盤鍵入負數。

解決方案是使用關鍵代碼來防止:

 // Select your input element. var number = document.getElementById('number'); // Listen for input event on numInput. number.onkeydown = function(e) { if(!((e.keyCode > 95 && e.keyCode < 106) || (e.keyCode > 47 && e.keyCode < 58) || e.keyCode == 8)) { return false; } }
 <form action="" method="post"> <input type="number" id="number" min="0" /> <input type="submit" value="Click me!"/> </form>

@Hugh Guiney提供的說明

正在檢查哪些關鍵代碼:

  • 95, < 106 對應數字鍵 0 到 9;
  • 47, < 58 對應於 Number Row 上的 0 到 9; 8 是退格。

因此,此腳本可防止在輸入中輸入無效密鑰。

對我來說,解決方案是:

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

編輯

正如評論中所建議的,如果 0 是最小值,則稍作更改即可工作。

 <input type="number" min="0" oninput="this.value = !!this.value && Math.abs(this.value) >= 0 ? Math.abs(this.value) : null">

這段代碼對我來說很好用。 你能檢查一下嗎:

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

簡單的方法:

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

如果輸入負數,我想允許十進制數字而不清除整個輸入。 這至少在 chrome 中運行良好:

<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 函數。

如上所述,它的作用相同。 如何解決問題只是個人喜好。

這是一個 angular 2 解決方案:

創建一個類 OnlyNumber

import {Directive, ElementRef, HostListener} from '@angular/core';

@Directive({
  selector: '[OnlyNumber]'
})
export class OnlyNumber {

  // Allow decimal numbers. The \. is only allowed once to occur
  private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);

  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];

  constructor(private el: ElementRef) {
  }

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    // Do not use event.keycode this is deprecated.
    // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    let current: string = this.el.nativeElement.value;
    // We need this because the current value on the DOM element
    // is not yet updated with the value from this event
    let next: string = current.concat(event.key);
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

將 OnlyNumber 添加到 app.module.ts 中的聲明中,並在您的應用程序中的任何地方像這樣使用它

<input OnlyNumber="true">

僅供參考:使用 jQuery,您可以使用以下代碼覆蓋 focusout 上的負值:

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

這不會取代服務器端驗證!

只需使用 min="0"

 <v-text-field v-model="abc" class="ml-1 rounded-0" outlined dense label="Number" type="number" min="0"> </v-text-field>

oninput="this.value=(this.value   < Number(this.min) || this.value   > Number(this.max))  ? '' : this.value;"

如果您不想用更多代碼弄臟 HTML,只需添加另一種方法(使用 Angular)

您只需要訂閱字段 valueChanges 並將 Value 設置為絕對值(注意不要發出新事件,因為這會導致另一個 valueChange 因此遞歸調用並觸發最大調用大小超出錯誤)

代碼

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

TypeScript CODE(在你的組件中)

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'];
}

限制類型 Number 中的字符 (-) & (e)

<input type="number" onkeydown="return event.keyCode !== 69 && event.keyCode !== 189" />

演示: https : //stackblitz.com/edit/typescript-cwc9ge?file=index.ts

 <input type="number" name="credit_days" pattern="[^\\-]+" #credit_days="ngModel" class="form-control" placeholder="{{ 'Enter credit days' | translate }}" min="0" [(ngModel)]="provider.credit_days" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" onpaste="return false">

對此的回答沒有幫助。 因為它僅在您使用向上/向下鍵時才有效,但如果您鍵入 -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();
    }
   });

此解決方案允許使用所有鍵盤功能,包括使用鍵盤復制粘貼。 它可以防止用鼠標粘貼負數。 它適用於所有瀏覽器, codepen上的演示使用 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;
    }
  });
});

這是一個最適合我的解決方案,適用於只允許數字的 QTY 字段。

// Only allow numbers, backspace and left/right direction on QTY input
    if(!((e.keyCode > 95 && e.keyCode < 106) // numpad numbers
        || (e.keyCode > 47 && e.keyCode < 58) // numbers
        || [8, 9, 35, 36, 37, 39].indexOf(e.keyCode) >= 0 // backspace, tab, home, end, left arrow, right arrow
        || (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + A
        || (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + C
        || (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + X
        || (e.keyCode == 86 && (e.ctrlKey === true || e.metaKey === true)) // Ctrl/Cmd + V
    )) {
        return false;
    }

 If Number is Negative or Positive Using ES6's Math.Sign const num = -8; // Old Way num === 0 ? num : (num > 0 ? 1 : -1); // -1 // ES6 Way Math.sign(num); // -1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM