Create button generate serial number

-1

So, I need to make a button that generates a serial, inside an input text when clicking. But the serial would need to contain [wf] [2017] as default and the rest random. Ex: wf2017892143.

I think it's with JS. But any idea how to make this button generating this random S / N?

    
asked by anonymous 21.09.2017 / 16:07

3 answers

-1

The html code:

<input type="text" value="" id="txt_serial">
<input type="button" value="gerar" id="botao_serial">

Import jquery:

<scritp src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

Thecodeusingjquery:

functiongeraSerial(){vartext="";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 6; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return "wf2017" + text;
}
$(function(){
    $('#botao_serial').click(function(){
        $('#txt_serial').val(geraSerial());
  });
});

Result: link

    
21.09.2017 / 16:22
10

Here's a suggestion. At least it generates wf20171000 , and all the IDs are unique.

You could use a more complex ID with uuid , which would be alpha numeric, but for what you described I think the example below works.

var geraNumeroUnico = (function() {
  var saidos = [];
  return function() {
    var numero = Math.round(Math.random() * 1e8) + 1000;
    if (saidos.includes(numero)) return geraNumeroUnico();
    saidos.push(numero);
    return numero;
  }
})();


function geraId() {
  return 'wf2017' + geraNumeroUnico();
}

// teste

for (var i = 0; i < 100; i++) {
  console.log(i, geraId());
}
    
21.09.2017 / 16:17
0

HTML / Javascript Solution:

<html>
    <head>
        <script>

            function gerar_string_aleatoria( tam, charset )
            {
                var serial = "";

                for( var i = 0; i < tam; i++ )
                    serial += charset.charAt( Math.floor(Math.random() * charset.length) );

                return serial;
            }


            function gerar_serial()
            {
                return 'wf2017' + gerar_string_aleatoria( 6, "0123456789" );
            }

        </script>
    </head>

    <body>
        <form name='frm'>
            <input type='text' name='txtSerial' value=''>
            <input type='button' name='btnGerarSerial' onClick='document.frm.txtSerial.value = gerar_serial();'>
        </form>
    </body>

</html>
    
21.09.2017 / 16:23