Search code examples
javascripthtmlradio-button

Why is the value of the radio button selected not updating?


Whenever I select a new radio button on my HTML, the function newChord() only outputs 1 to the console, no matter the option. For example, if I've selected the button Advanced instead of Beginner, the console should show 3 (associated to Advanced through JS), but it's still only showing 1 (associated to Beginner). The leads me to believe that there's something wrong with the if statements (vague I know...) but I can't figure out why it's working for the beginner option, but not any of the others.

HTML Code

<div class="difficulty_btn"><br>
          <form>
            <input type="radio" id="beginner_btn" name="difficulty" value="beginner" checked>
            <label for="beginner_btn">Beginner</label>

            <input type="radio" id="intermediate_btn" name="difficulty" value="intermediate">
            <label for="intermediate_btn">Intermediate</label>

            <input type="radio" id="advanced_btn" name="difficulty" value="advanced">
            <label for="advanced_btn">Advanced</label>

            <input type="radio" id="mixed_btn" name="difficulty" value="all">
            <label for="mixed_btn">Mixed</label>

          </form><br>
</div>

Javascript Code

function newChord() {
    
    if ($("input[name='difficulty']:checked").val('beginner')) {
        console.log(1);
        
    } else if ($("input[name='difficulty']:checked").val('intermediate')) {
        console.log(2);

    } else if ($("input[name='difficulty']:checked").val('advanced')) {
        console.log(3);
        
    } else if ($("input[name='difficulty']:checked").val('all')) {
        console.log(4);
    }
}

Any help is appreciated, thanks in advance.


Solution

  • This line

    if ($("input[name='difficulty']:checked").val('beginner'))
    

    is not comparing the checked attribute's value, it's assigning it.

    You probably want something like this instead:

    if ($("input[name='difficulty']:checked").val() == 'beginner') {
        console.log(1);
    } else if ($("input[name='difficulty']:checked").val() == 'intermediate') {
        console.log(2);
    }
    .... and so on