Do not insert zeros to the left of a number

4

I have n inputs, which are created dynamically. What happens is that they can not accept leading zeros on the following occasions:

0.24 - > The system accepts

00.24 - > The system automatically removes the leading zero to 0.24

034.55 - > The system automatically removes the leading zero to 34.55

That is, the leading zero is only possible when it is leaning to the left of the point.

To do for all inputs dynamically, I'm starting with the following function:

$(document).ready(function () {
    $('input').keypress(function(e) {
        // Verificar os zero à esquerda     

        }
    });
});

Is it possible here, check these conditions from the leading zero? Or using onchage?

    
asked by anonymous 18.03.2016 / 10:30

2 answers

6

Follow an example using setInterval .

It was done this way to work directly on value, regardless of how data was entered.

Test here:

var l = document.getElementsByClassName( 'zeros' );
setInterval( function(){
  for ( var i = 0; i < l.length; i++ ) {
    while( l[i].value.length > 1 && l[i].value.substring( 0, 1 ) == '0' && l[i].value.substring( 0, 2 ) != '0.' ) {
      var s = l[i].selectionStart;
      l[i].value = l[i].value.substring( 1 );
      l[i].selectionEnd = l[i].selectionStart = s - 1;
    }
  }
}, 75);
<input class="zeros" type="text"><br>
<input class="zeros" type="text"><br>
<input class="zeros" type="text"><br>

Features:

  • It works by typing, copying, and deleting characters;

  • works even if the text is changed by JS because it is content-based;

  • Finds fields by class, making it easy to implement.

18.03.2016 / 11:08
1

This regular expression replaces the surplus characters. In your case, the leading zeros.

str = '0000.00';
str = str.replace(/^0+(?!\.|$)/, '');
console.log(str);
    
18.03.2016 / 11:08