簡體   English   中英

文本輸入只允許在容器中輸入數字

[英]Text Input allow only Numeric input in container

所以我在 javascript put 中輸入了我不知道如何只使用數字輸入,我嘗試使用數字類型 put 它只在我以字母開頭時才有效,但是當我以數字開頭然后添加字母時,它會留下輸入字段中的字母,所以我的輸入容器是:

var td = document.createElement("td");
    var input = document.createElement("input");
    input.type = "number";
    input.name = "//retseptid/retsept[" + count + "]/doos";
    input.id = "prescription_" + count + "_dosage";
    input.value = UTF8Decode(prescription.doos);
    input.className = "txt_left";
    input.style.width = "52px";
    if(prescriptionContainerIsDisabled) {
        input.disabled = true;
    }
    else {
        addChangeListener(input);
    }
    td.appendChild(input);

    td.appendChild(document.createTextNode(" "));

我認為,我不能在這里使用onkeypress是結果,並且必須只輸入數字的字段在此處輸入圖片說明

您可以創建一個函數來檢查它是否是數字並在輸入的onkeypress事件上調用該函數:

function isNumber(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
        window.alert("Your entry must be numeric!");
        return false;
    }
    return true;
}

試試這個來定義你的onkeyup事件。 注意沒有"

input.onkeyup = function(evt) {return isNumber(evt);};

所以最終對我有用的是函數:

function isNumber()
{
      this.value = this.value.replace(/,/g, '.');
      this.value = this.value.replace(/^\./, "0.");
      this.value = this.value.replace(/[^0-9\.]/g, '');
      var match = this.value.match(/\d*\.\d*/);
      if (match)
         this.value = match[0];
}

我這樣稱呼它:

input.onkeyup = isNumber;

暫無
暫無

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

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