DEV Community

Walter Nascimento
Walter Nascimento

Posted on

Random Number Draw

Using JavaScript, let's create a random number draw

Code

HTML

<fieldset>
  <legend>Sorteio</legend>
  <label>Sortear</label>
  <input type="number" id="inputEl" minlength="1" />
  <span>número(s)</span>

  <label>Entre</label>
  <input type="number" id="inputIniEl" minlength="1" />

  <label>e</label>
  <input type="number" id="inputEndEl" minlength="1" />

  <button id="playEl">Sorteio</button>
</fieldset>

<fieldset id="resultEl" style="display: none">
  <legend>Resultado</legend>
  <table>
    <thead>
      <th>Ordem</th>
      <th>Número</th>
    </thead>
    <tbody id="outputEl"></tbody>
  </table>
  <div>
    Sorteio realizado em: <strong id="dateEl"></strong> às
    <strong id="timeEl"></strong>
  </div>
</fieldset>
Enter fullscreen mode Exit fullscreen mode

This code defines a web page with two fieldset elements. The first one is labeled "Sorteio" and has several input elements, including:

  • a number input element with the id "inputEl"
  • a number input element with the id "inputIniEl"
  • a number input element with the id "inputEndEl"

It also contains a button element with the id "playEl" labeled "Sorteio", which will likely initiate the sorteio.

The second fieldset element is labeled "Resultado" and has an id "resultEl" and is hidden by default. It contains:

  • a table element with headings "Ordem" and "Número"
  • a tbody element with id "outputEl" that will likely be populated with the results of the sorteio.
  • a div element displaying the date and time of the sorteio.

It looks like this code is meant to be used as a simple page that allows a user to input a range of numbers, specify how many numbers they want to randomly select from that range, and then generate the results of the random selection and display them in a table on the page.

JS

'use strict';

playEl.addEventListener('click', main);

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

function dateNow(input = Date.now()) {
  let date = new Date(input);
  let localeDate = date.toLocaleDateString('pt-BR', { dateStyle: 'long' });
  let localeTime = date.toLocaleTimeString('pt-BR', { timeStyle: 'medium' });
  return { localeDate, localeTime };
}

function generateTable(table, data) {
  for (let [key, value] of data.entries()) {
    let row = table.insertRow();
    let cell = row.insertCell();
    let text = document.createTextNode(`${key + 1}°`);
    cell.appendChild(text);

    cell = row.insertCell();
    text = document.createTextNode(`${value}`);
    cell.appendChild(text);
  }
}

function main() {
  resultEl.style.display = 'none';
  let loop = inputEl.value;
  let ini = parseInt(inputIniEl.value);
  let end = parseInt(inputEndEl.value) + 1;
  let result = [];

  while (loop) {
    let random = getRandom(ini, end);
    if (!result.includes(random)) {
      result.push(random);
      loop--;
    }
  }

  outputEl.innerHTML = '';
  generateTable(outputEl, result);

  let { localeDate, localeTime } = dateNow();
  dateEl.innerHTML = localeDate;
  timeEl.innerHTML = localeTime;
  resultEl.style.display = 'block';
}
Enter fullscreen mode Exit fullscreen mode
  • The first line 'use strict'; is a statement that enables strict mode, which is a way to opt in to a restricted variant of JavaScript.

  • The second line playEl.addEventListener('click', main); is adding an event listener to the button element with the id "playEl" that listens for a 'click' event and calls the function main when it occurs.

  • The getRandom(min, max) function takes in two arguments, min and max, and returns a random number between those two values, using the Math.random() and Math.floor() methods.

  • dateNow(input = Date.now()) is a function that takes an optional input which is the current date time by default and returns an object that contains the date and time.

  • The generateTable(table, data) function takes two arguments, table and data, and generates a table from the data. It loops through the data, creates a new row for each value, and inserts the value into the table.

  • main() is the main function that is called when the button is clicked. It starts by hiding the result fieldset element, then it gets the user input values, generates random numbers, and populates the output table. Then it generates the date and time of the sorteio, and shows the result fieldset element.

Demo

See below for the complete working project.

if you can't see it click here and see the final result


Thanks for reading!

If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!

😊😊 See you later! 😊😊


Support Me

Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso

Top comments (0)