-1

So I have have input in javascript put I cant figure out how to only use numeric input, I tried using the numeric type put it only worked if I starded with letters, but when I start with numbers and then add letters, then it leaves the letter in the inputfield, so my container for the input is:

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(" "));

I think, that I cant use onkeypress here is the outcome, and the field that has to let only numbers to be inputed enter image description here

Kalev Kalm
  • 39
  • 7
  • 1
    duplicate of http://stackoverflow.com/questions/469357/ – mccainz Jun 29 '15 at 13:26
  • its not a duplicate, if it were, I would have got some help from those postst, give me a solution if youre so familiar with the other posts and you guys tell that mine is a copy – Kalev Kalm Jun 29 '15 at 13:57
  • Note that reviews are not personal criticisms but rather part of the process of keeping SO usable. Flagging as a duplicate will only result in multiple other users examining to determine if the question is truly a duplicate or not. – mccainz Jun 29 '15 at 15:11

2 Answers2

1

You can create a function to check if it is a number and call that function on your input's onkeypress event:

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

Try this to define your onkeyup event. Notice no ".

input.onkeyup = function(evt) {return isNumber(evt);};
brso05
  • 13,142
  • 2
  • 21
  • 40
0

So in the end what did it for me was the function:

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

and I called it like this:

input.onkeyup = isNumber;
Kalev Kalm
  • 39
  • 7