skip to Main Content

i am making a quiz and i want to find out which button has the most clicks so i can give the answer

i have these variables in the start set to zero and their scores will increase by user input
var earthScore = 0; var venusScore = 0;
whenever the button is clicked a fuction runs
q1a4.addEventListener ("click", earth); q1a5.addEventListener ("click", venus);
this function will add one to the original variables
function earth () { earthScore += 1; questionCount += 1; }
function venus () { venusScore += 1; questionCount += 1; }
now i want to find out the variable which has the most clicks and give an answer to user so for example; if earth variable has greater score than venus variable then i will change the result to result.innerHTML = 'you are earth' but i don’t know how to find the variable with the greatest score

this is actually my first project using js so i dont have that much idea and everything i tried to find seems wrong so i would really appreciate if anyone can give me an answer for my program.

2

Answers


  1. You might put the Results into an Array afterwards with:

    let tmpArray = [];
    tmpArray.push(earth);
    tmpArray.push(venus);
    tmpArray.sort(function(a, b){return b - a});
    

    Now, you have the highest value in:

    tmpArray[0];
    

    Refer to: https://www.w3schools.com/js/js_array_sort.asp

    Login or Signup to reply.
  2. Take a look at the solution first:

    var earthScore = 0;
    var venusScore = 0;
    var questionCount = 0;
    
    function handleResult() {
        if (earthScore !== venusScore) result.innerText = "you are " + ((earthScore >= venusScore) ? "earth" : "venus");
        else result.innerText = "";
    }
    
    function earth () { earthScore += 1; questionCount += 1; handleResult(); }
    function venus () { venusScore += 1; questionCount += 1; handleResult(); }
    
    let q1a4 = document.getElementById("q1a4");
    let q1a5 = document.getElementById("q1a5");
    
    q1a4.addEventListener ("click", earth); q1a5.addEventListener ("click", venus);
    
    let result = document.getElementById("result");
    <input type="button" id="q1a4" value="EARTH">
    <input type="button" id="q1a5" value="VENUS">
    <div id="result"></div>

    Explanation:

    • we initialize the scores with 0
    • we define handleResult which will update the result with the current winner (or nothing when we have a tie)
    • we have earth and venus like you initially defined, except for calling handleResult as well to handle the result
    • we get the buttons
    • we specify click events for the buttons like you specified
    • we get the result element as well so we can display the result
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search