Jen
Jen

Reputation: 1733

Input[type=number] without multiple decimals

I would like to make an input[type=number] which disallows multiple decimals and all non-numbers including the letter e. The trouble is, regex that work for input[type=text] don't work for input[type=number].

When I log to console the value of a number input with multiple decimals, the value is empty.

Here is Codepen : https://codepen.io/btn-ninja/pen/oNxRoJN?editors=1111

HTML

  <input type="number" 
   class="isDecimal" 
   placeholder="Type 2.3.4 and watch console"
   maxlength="20"> 

JS

$('.isDecimal').on("input", function(e) {
  var num = $(this).val().toString();
  console.log(num);
});

Upvotes: 0

Views: 79

Answers (1)

Jerson
Jerson

Reputation: 1745

let lastValidInputValue;
let selectedDot = false;


const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};


const onInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }
<input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">

this original posted in this question

Upvotes: 1

Related Questions