-1

I have an input value that excepts decimal numbers but the problem is that the decimal point or the period point repeat more than one time inside the input value for example 1.2.3 instead of this 1.23 thank you.

           let input = document.querySelectorAll("input")

              let arr = []

           function period_noRepeat(x){
              const result = []
             const input = Array.isArray(x)? x: x.split('')

             for(let i = 0; i < input.length; ++i){
             if(input[i] == input[i + 1] && input[i] != 1 * input[i]) continue
           result.push(input[i])
             }

            return result;
            }

            const regex = /[^0-9\.]/
           input.forEach(function(item){
              item.addEventListener("input",function(e){

              item.value = item.value.replace(regex,"")

             arr = item.value.split("")


             item.value = period_noRepeat(arr).join("")




         })



        })
                <input type="text" class="dividend" >
               <input type="text" class="divisor" dir = "rtl">
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
Yyuv Ali
  • 13
  • 6
  • Did you try by using `` instead of ``? – Raffaele May 10 '20 at 08:55
  • But that's not what I want that one is boring. – Yyuv Ali May 10 '20 at 08:56
  • Well, that will fix the issue, if that's not good enough, I'm creating a code for that, you can see in few seconds as answer in this page. – Raffaele May 10 '20 at 09:09
  • Does this answer your question? [Match only numbers including decimals](https://stackoverflow.com/questions/61706218/match-only-numbers-including-decimals) – SMAKSS May 10 '20 at 09:28
  • 1
    `item.value = item.value.replace(/(\.[^.]*)\./, "$1").replace(/^\.|[^\d.]/, "").replace(/^0[^.]/, "0")` – MikeM May 10 '20 at 11:31
  • 1
    Or with backreferences just: `item.value = item.value.replace(/(?<=\..*|^)\.|(?<=^0)\d|[^\d.]/, "")` – MikeM May 10 '20 at 11:33

2 Answers2

1

Try to use this one:

^-?[0-9]\d*(\.\d+)?$

(\.\d+)? will assure your decimal fraction will only repeats one time.

SMAKSS
  • 9,606
  • 3
  • 19
  • 34
0

There is a feature from the callback associated to the events, to avoid the event's effect: event.preventDefault(). You can use in this way:

// inside the input.forEach callback:
item.addEventListener('keydown',event => {
    var isDotPresent = item.value.indexOf('.')>-1;
    var isDotInput = event.key==='.';

    // I have to avoid the dot:
    if (isDotPresent && isDotInput) {
        // avoid the effect of the event (so the injection of dot into the text)
        event.preventDefault();
    }
});

Raffaele
  • 737
  • 7
  • 21