0

I have this Jquery function:

if ($("#nuevaFactura").is(':selected')) {
        $("#nuevoDocumentoValorHidden").val('00001');
        $("#nuevoDocumentoValor").val(idDocumento+'-'+'0001');
        $("#idDocumento").val($("#nuevaFactura").val());
      }

However, when the value reaches 10, the result I get is '000010', and my target is to get '0010'. And for 100, I would like '00100'. Is there a function in Jquery to get this result?

Joe Hilton
  • 25
  • 1
  • 5

1 Answers1

0

Assuming you want a fixed 4 digit number with leading zeros, you can do it using the slice() method of JQuery like this:

/* A fixed pattern of leading zeros */
var pattern = "0000";

/* The real integer number */
var num = 10;

/* Now, get the latest 4 characters of the concatenation string */
/* Example: <pattern + num> will be equal to: 000010 */
/* But latest 4 digits will be: 0010 */
(pattern + num).slice(-4);

Check next example:

/* A fixed pattern of leading zeros */
var pattern = "0000";

/* Sample of numbers */
var nums = [1, 10, 56, 100, 715, 1000, 2206];    

/* Now, format the number with leading zeros */
    
nums.forEach(function(num)
{
    console.log((pattern + num).slice(-4));
});
Shidersz
  • 16,846
  • 2
  • 23
  • 48
  • This is a great solution. However, the problem comes in when you are getting the values from a database. For example, i just saved Invoice "0001". For getting next invoice displayed in screen, if I use your solution, I will just get "0000002". Do you get me? – Joe Hilton Nov 17 '18 at 16:26
  • 1
    Nope, i don't get you, can you make a better explanation? My solution will never return a string with more than 4 digits. – Shidersz Nov 17 '18 at 16:32