자바스크립트 오류 문의 (랜덤추첨기)

자바스크립트 오류 문의 (랜덤추첨기)

QA

자바스크립트 오류 문의 (랜덤추첨기)

본문

아래의 소스에서 "응모자 목록" 을 10명으로 만들었는데 2명을 뽑으려고 하니 아래와 같은 오류가 뜹니다\

어디를 수정해야 할까요 ㅠㅠ

 

1889747412_1674034559.386.png

 



<!doctype html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <META NAME="Keywords" CONTENT="당첨자 추첨하기, 추첨하기, 컴퓨터 추첨">
    <META NAME="Description" CONTENT="당첨자 추첨하기, 추첨하기, 컴퓨터 추첨">
    <title>당첨자 추첨하기</title>
    <link rel="icon" href="//apps.ojj.kr/favicon.ico" type="image/x-icon">
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
    <style>
        td {font-size : 10pt; line-height:140%; font-family:dotum;}
        .header_title {
            font-family: verdana;
            font-weight: bold;
            font-size: xx-large;
            text-decoration: none;
            color:NAVY;
        }
        .table_frame {
            width: 100%;
            max-width: 600px;
            /*text-align: center;*/
            margin: auto;
            border: none;
            align-self: center;
        }
    </style>
</head>
<body style="margin-top: 70px">
<script type="text/javascript">
    function count_apply_list()
    {
        var form = document.winnerForm;
        var lines;
        form.apply_list.value = form.apply_list.value.trim();
        lines = form.apply_list.value.split(/\r\n|\r|\n/);
        form.apply_count.value = lines.length;
    }
    function get_winner()
    {
        var form = document.winnerForm;
        var lines = [];
        //var apply_list = new String(form.apply_list.value);
        var winner_list = []
        var winner_count = 0;
        apply_list = form.apply_list.value;
        if ( apply_list.length == 0 )
        {
            alert('응모자 목록을 2명(줄) 이상 입력하세요. ');
            form.apply_list.focus();
            return;
        }
        lines = apply_list.split(/\r\n|\r|\n/);
        form.apply_count.value = lines.length;
        //alert(lines.length);
        if ( lines.length < 2 )
        {
            alert('응모자 목록을 2명(줄) 이상 입력하세요. ');
            form.apply_list.focus();
            return;
        }
        if ( form.winner_count.value == '' )
        {
            alert('당첨자 수를 입력하세요.  ');
            form.winner_count.focus();
            return;
        }
        else if ( isNaN(form.winner_count.value) )
        {
            alert('당첨자 수를 숫자로 입력하세요.  ');
            form.winner_count.value='';
            form.winner_count.focus();
            return;
        }
        else if ( form.apply_count.value <= form.winner_count.value )
        {
            alert('당첨자 수는 응모자 수(' + form.apply_count.value + ')  보다 작아야 합니다.   ');
            form.winner_count.value='';
            form.winner_count.focus();
            return;
        }
        winner_count = form.winner_count.value;
        i=0;
        while ( winner_list.length < winner_count )
        {
            rand_num = Math.floor(Math.random()*lines.length);
            check_dup = 0;
            for (j=0; j < winner_list.length ; j++ )
            {
                if ( winner_list[j] == rand_num)
                {
                    check_dup = 1;
                    break;
                }
            }
            // if not exist in winner_list
            if ( check_dup == 0 )
            {
                winner_list[i] = rand_num;
                i++;
            }
        }
        winner_list.sort();
        form.winner_list.value = '';
        for (idx=0; idx < winner_list.length ; idx++)
        {
            form.winner_list.value += lines[winner_list[idx]] + '\n';
        }
    }
</script>
<div style="margin:auto; text-align: center; max-width: 480px">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5949021124468292"
     crossorigin="anonymous"></script>
<!-- 수평형_468x80 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:100%; max-width:468px;height:80px"
     data-ad-client="ca-pub-5949021124468292"
     data-ad-slot="9064649802"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<br>
<form name="winnerForm" method="POST">
    <table border=1 cellspacing=1 cellpadding=2 align="center" style="width:100%; max-width: 600px">
        <colgroup>
            <col width=100>
            <col width=*>
        </colgroup>
        <tr><td align="center"><b>응모자 목록</b><br>
                <input type=text name="apply_count" value=0 size=2 readonly style="text-align:center;"></td>
            <td><textarea name="apply_list" style="width:100%; height:200px" onChange="count_apply_list()"></textarea>
                <br>
                <font color=RED>명단은 줄바꿈으로 구분됩니다.</font>
            </td>
        </tr>
        <tr><td align="center"><b>당첨자 수</b></td>
            <td><input type="text" name="winner_count" value="1" size=3 maxlength=3> 예) 10 (응모자 수 보다 작게)</td>
        </tr>
        <tr><td align='center'><b>추첨 결과</b></td>
            <td>
                <div style="margin:auto; text-align: center; max-width: 480px">
                    <ins class="kakao_ad_area" style="display:none;" 
 data-ad-unit    = "DAN-WswNxNi4Q0n5chBG" 
 data-ad-width   = "320" 
 data-ad-height  = "100"></ins> 
<script type="text/javascript" src="//t1.daumcdn.net/kas/static/ba.min.js" async></script>
                </div>
                <textarea name="winner_list" style="width:100%;height:200px"></textarea>
            </td>
        </tr>
  </table>
    <br>
    <div style="margin:auto; text-align: center; max-width: 480px">
        <input type="button" value="    추첨!    " onClick="get_winner();">
    </div>
</form>
<br>
<div style="margin:auto; text-align: center; max-width: 480px">
    <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5949021124468292"
     crossorigin="anonymous"></script>
<!-- 수평형_468x80 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:100%; max-width:468px;height:80px"
     data-ad-client="ca-pub-5949021124468292"
     data-ad-slot="9064649802"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<br>
<script>
    document.write('<div style="margin:auto; text-align:center; color:#ffffff">현재 모니터 해상도:\n\n' + screen.width + 'x' + screen.height + '</div>');
</script>

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-1716705-1"></script> 
<script> 
  window.dataLayer = window.dataLayer || []; 
  function gtag(){dataLayer.push(arguments);} 
  gtag('js', new Date()); 
  gtag('config', 'UA-1716705-1'); 
</script>
<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>
<script type="text/javascript">
if(!wcs_add) var wcs_add = {};
wcs_add["wa"] = "cafbfb9609c988";
wcs_do();
</script>

</body>
</html>

 

이 질문에 댓글 쓰기 :

답변 2


// else if ( form.apply_count.value <= form.winner_count.value )
else if ( Number(form.apply_count.value) <= Number(form.winner_count.value) )

베르만님 답변처럼 자바스크립트에서는 숫자인지 문자인지 모를때는 그냥 문자로 비교해버립니다.

사람은 숫자라고 생각하지만서도요

winner_count는 value 에 "1"이라고 되어있지만 문자로 인식하고

apply_count는 value에 0 이라고 되어있으니 숫자로 인식할것 같지만 실제로는 비교가 제대로 안될것 같네요

형변환을 통해 비교일치를 시키신후 확인해보시길 바랍니다.

 

답변을 작성하시기 전에 로그인 해주세요.
전체 1,121
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT