I\'ve created some simple lottery function in JS. All works fine.
The only issue I\'m facing is how to display all numbers which have been guessed?
I have 6 ind
What the below still misses is to make sure the user don't repeats numbers in the inputs.
I won't do that since I would neither use inputs for that purpose, but rather predefined checkboxes (yes, 38 checkboxes) and make sure , on submit, exactly 6 are checked.
Anyways, hope this might be helpful:
function lottoGenerate(min, max) {
// Shuffle: https://stackoverflow.com/a/6274381/383904
const a = Array.from({length: max}, (_, v) => v + 1);
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a.slice(0, min);
}
function play() {
const guessed_nums = [];
const lotto_nums = lottoGenerate(6, 38); // Generate 6 random unique lotto numbers
const player_nums = Array.from(document.querySelectorAll('.num')).map(el => {
const n = parseInt(el.value, 10);
const isGuessed = lotto_nums.includes(n);
if (isGuessed) {
guessed_nums.push(n); // Insert the guessed number!
el.style.background = 'lightgreen';
} else {
el.style.background = 'red'
}
return n
});
document.getElementById('gen').textContent = lotto_nums.join(', ');
document.getElementById('player').textContent = player_nums.join(', ');
document.getElementById('response').innerHTML = `
You guessed ${guessed_nums.length} numbers!<br>
The numbers are: ${guessed_nums.join(', ')}
`;
}
document.getElementById('play').addEventListener('click', play);
<input class="num" type="number" min=1 max=38 value="1">
<input class="num" type="number" min=1 max=38 value="2"><br>
<input class="num" type="number" min=1 max=38 value="3">
<input class="num" type="number" min=1 max=38 value="4"><br>
<input class="num" type="number" min=1 max=38 value="5">
<input class="num" type="number" min=1 max=38 value="26"><br>
<button id="play">PLAY LOTTO 6/38</button>
<div>Numbers: <span id="gen"></span></div>
<div>User played: <span id="player"></span></div>
<div id="response"></div>