0

My code is supposed to update "level" to the value of "level_num" but instead, it keeps returning 0.

function find_level() {
    let level_num = 0;
    document.querySelector("#easy").onclick = () => {
        document.querySelector("h3").innerHTML = `You chose Easy. Good Luck!`
        level_num =  1;
    }

    document.querySelector("#medium").onclick = () => {
        document.querySelector("h3").innerHTML = `You chose Medium. Good Luck!`
        level_num = 2;
    }

    document.querySelector("#hard").onclick = () => {
        document.querySelector("h3").innerHTML = `You chose Hard. Good Luck!`
        level_num =  3;
    }
    return level_num;
}

document.addEventListener('DOMContentLoaded', function() {

    let level = find_level();
    document.querySelector("h1").innerHTML = `You chose ${level}. Good Luck!`
})
Yi Mas
  • 11
  • 1
  • 4
    your function doesn't change `level_num` it just reassigns the `onclick` callback of each element and then returns the unchanged value of `0` – pilchard May 24 '22 at 23:44
  • For example, replace `level_num = 1;` with `document.querySelector("h1").innerHTML = \`You chose 1. Good Luck!\`;`. I don't think you need the `find_level` function, and execution, at all. – bloodyKnuckles May 24 '22 at 23:49
  • I want this function to return a certain value based on what level the user clicks so that I can use the value in future functions if that makes sense. – Yi Mas May 24 '22 at 23:52
  • 1
    Then have a global variable `level_num` and leave `level_num = 1;` (with corresponding value) in each event listener, just add `document.querySelector("h1").innerHTML = \`You chose 1. Good Luck!\`;` – bloodyKnuckles May 24 '22 at 23:54
  • See: https://jsfiddle.net/9fdmg3wp/ – bloodyKnuckles May 25 '22 at 00:04

0 Answers0