Put a certain amount of zeros with jQuery

2

Hi, I have a small problem:

I have my table in my BD called numeracion , in which is the field numeracion in it I have the numbers of the tickets or invoices;

id_numercion      numeracion      id_estado
----------        ----------      ----------
1                 1               1
2                 2               1
3                 3               1

This is the QUERY FORMED WITH THE DIFFERENT TABLES as you see there is a beginning and an end

Well that's the table, in my JQuery I get the highest numbering, for example the 3 but that number grows up to 500 ,

What I want is that by pulling the number in this case the 3 put it in my div as 003 and when it reaches 10 put it as 010

This is my ajax in jQuery

    function traer_numeracion(id_recibo) {
    //    console.log(id_recibo);
        $.ajax({
            type: 'POST',
            url: baseurl + 'Venta/traer_numero',
            data: {id_recibo: id_recibo},
            cache: false,
            dataType: "JSON",
            success: function (data)
            {
                var numero = data[0]['numeracion']
                if (numero == null || numero == "") {
                    //si el valor esta vacio me pone el valor por defecto que es 1
                    $('#numero_recibo').html("Nº " + data[0]['serie'] + '-' + data[0]['numero_inicio']);
                    $('#id_numeracion').val(data[0]['id_serie']);
                    $('#numeracion_data').val(data[0]['numero_inicio']);
                } else {
                    console.log(numero.length);
                    numero = parseInt(numero) + 1;
                    $('#numero_recibo').html("Nº " + data[0]['serie'] + '-' + numero);
                    $('#id_numeracion').val(data[0]['id_serie']);
                    $('#numeracion_data').val(numero);
                }
            },
            error: function (result) {
            }
        });
    }

What I want: What I have so far:

    
asked by Ivan More Flores 12.07.2017 в 22:48
source

6 answers

1

The best way to do it is: ("0000" + num).substr(-4,4) . The "0000" is with the string you want to fill, then with the substr the positions you want the new string to have.

  

link

    
answered by 12.07.2017 / 22:58
source
1

You can try something like this:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"

var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"
    
answered by 12.07.2017 в 22:55
1

One way would be to work with the method slice()

let num1 = 1;
let num2 = 10
let num3 = 100;
let num4 = 1000;

console.log( ('000' + num1).slice(-4) ); // "0001"
console.log( ('000' + num2).slice(-4) ); // "0010"
console.log( ('000' + num3).slice(-4) ); // "0100"
console.log( ('000' + num4).slice(-4) ); // "1000"
    
answered by 12.07.2017 в 23:08
1

EDIT

When loading the number, just replace it with a 3-digit format. The replace function is perfect for this case.

function format4d(numero){
    return numero.text().replace(/(\d)(?=(\d\d\d\d)+(?!\d))/g, "$1,");
}
$('#numeracion_data').val(format4d(data[0]['numero_inicio']));

Yes it is only to show on the screen you can format in this way at the time of printing.

  

Now if you always want to have this form I recommend you give them the   format when you save it and change your data types to varchar   in your database so that they are preserved.

    
answered by 12.07.2017 в 22:55
1

The function you are looking for in a pad , there is a function that I use for it:

function pad(num, largo, char) {
    char = char || '0';
    num = num + '';
    return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
}

alert(pad(15, 4, '0'));
    
answered by 12.07.2017 в 23:21
1

The ideal function would be padStart() .

The only problem is that, at least for now , it is not compatible with all browsers, including Internet Explorer. However, as the same documentation says, it is currently a ECMA Script proposal , which possibly It does not take long to reach the main browsers.

It is important not to lose sight of it, since in several of the solutions that exist so far , the performance can be more or less affected if we use a function for fill zeros in long loops.

You can find complete information about her in the doc de MDN :

  

The padStart() method fills the current string with a given string   (repeated eventually) so that the resulting string reaches a   given length. The filling is applied from the beginning (left) of   the current chain.

Here is a code example of what would be a zerofill handmade function.

Calling the function in this way, for example: zerofill(5,0) fills you with zeros to the left until you reach a maximum of 5 characters.

It works not only with numbers, but with any other character.

/*
  * pos:  cantidad de  dígitos totales
  * fill:  caracter  de relleno
*/
function zerofill (pos,fill)
{
  var data=document.getElementById("datos").value;
  console.log(data.padStart(pos, fill));
}
<input id="datos" type="text" value="" size="35" placeholder="Introduzca un valor y pulse rellenar">
<input type="button" value="Rellenar" onclick="zerofill(5,0);">
    
answered by 13.07.2017 в 00:10