简体   繁体   中英

How to use id in switch statement and alert the message when the button is clicked

I'm trying to make a question and answer quiz using html and js. I have written a question below and when the answer button is clicked, the corresponding answer should be displayed in a popup box (using alert).The id="lbutton" is used to style the button. Here is a html code

<div class="lmain">

                <p>
                main()
                {
                   char A = 'a' ;
                   int B = 'a' ;
                   if ( A == B )
                     printf ( "True" ) ;
                   else
                     printf ( "False" ) ;
                }

                </p>
                <button id="lbutton" onclick="myFunction()">Answer</button>
                <p id="cb2"></p>
    </div>

The javascript code goes like this

<script type="text/javascript">
            function myFunction(id)
            {
                if(id=='cb1')
                {
                    alret('24');
                }

                else if(id=='cb2')
                {
                    alert('True');
                }

            }

i'm new to js and im not sure how it works. So how to change the js code to implement the required condition.

<p>Q : 1</p>
<button class="lbutton" onclick="showAnswer(1)">Answer</button>

<p>Q : 2</p>
<button class="lbutton" onclick="showAnswer(2)">Answer</button>

<p>Q : 3</p>
<button class="lbutton" onclick="showAnswer(3)">Answer</button>

function showAnswer( questionNumber ){
    switch (questionNumber){
        case 1 : alert('Answer 1'); break;
        case 2 : alert('Answer 2'); break;
        case 3 : alert('Answer 3'); break;
        case 4 : alert('Answer 4'); break;
        default : alert('sorry there was an error in program');
    }
}

http://jsfiddle.net/qGGUg/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM