본문으로 바로가기

 

참여인원:

추첨인원:

[결과]
 
<script src="https://cdn.tailwindcss.com"></script>
<script>
    function randomNumbers() {
      let arr = []
      const result = document.querySelector('#result')
      result.innerHTML = ''
      const max = document.querySelector('#max').value
      const tot = document.querySelector('#tot').value
      const divwrap = document.createElement('div')
      if (tot >= max) {
        alert('추첨인원은 총인원보다 적어야합니다.')
      	return
      }
      divwrap.className = 'flex items-center gap-2 flex-wrap'
      while (arr.length < tot) {
        let num = Math.floor((Math.random() * max) + 1)
        if(arr.indexOf(num) > -1) {	// 중복검사
          continue
        } else {
          let div = document.createElement('div')
          div.innerText = num
          div.className = 'inline-block'
          divwrap.appendChild(div)
          arr.push(num)
        }
      }
      console.log(arr, 'arr?')
      const totdiv = document.createElement('div')
      totdiv.className = 'w-full text-center'
      totdiv.innerText = `${arr.length}명 추첨 완료`
      result.appendChild(totdiv)
      result.appendChild(divwrap)
    }
    window.onload = function() {
      document.getElementById('randomBtn').addEventListener('click', randomNumbers)
    }
</script>
<div class="w-full h-full p-8">
  <div class="w-full h-max flex flex-col justify-center gap-y-4">
    <div class="border-y rounded py-2">
      <div class="flex items-center justify-center gap-x-4">
        <p class="" data-ke-size="size16">참여인원:</p>
        <input id="max" class="border w-16 text-center" type="number" value="97" />
      </div>
      <div class="flex items-center justify-center gap-x-4">
   	    <p class="" data-ke-size="size16">추첨인원:</p>
        <input id="tot" class="border w-16 text-center" type="number" value="12" />
      </div>
    </div>
    <div class="w-fit mx-auto">
   	  <button id="randomBtn" class="border w-36 h-8 rounded bg-gray-400 text-white hover:bg-black" type="button">
   	    추첨하기
      </button>
    </div>
    <div class="w-full h-auto px-4 py-2 border-y rounded flex flex-col items-center justify-start">
      <div class="w-full text-lg text-center">[결과]</div>
      <div id="result" class="max-w-full flex-wrap">&nbsp;</div>
    </div>
  </div>
</div>
반응형