How to change img with JavaScript using radio button and switch case?

I want to have a background image depending on the checked radio button, using a switch case. However I'm not finding the right solution to get the value from the checked radio button.

Snippet of my code:

HTML:

<section class="configurator__product">
       ...
</section>

<label for="blue" class="hidden">Blue</label>
<input type="radio" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">
<label for="green" class="hidden">Green</label>
<input type="radio" id="green" name="color-totebag" value="tote-green" class="circle tote-green">
<label for="black" class="hidden">Black</label>
<input type="radio" id="black" name="color-totebag" value="tote-black" class="circle tote-black">

There's more inputs, 5 in total, hence the reason I don't think using if/else is optional. But I hope it gets clear with the amount of code I'm giving here.

JavaScript:

const changeTotebagColor = () => {
    let totebagColor = document.getElementsByName(`color-totebag`).value;
    const $totebagImg = document.querySelector(`.configurator__product`);

    switch (totebagColor) {
        case `tote-blue`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_blue')";
        case `tote-green`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_green')";
        case `tote-black`:
            $totebagImg.style.backgroundImage = "url('assets/img/totebag_black')";
    }
}

changeTotebagColor();

I hope it's a bit clear to what I'm trying to figure it out. I'm new to JavaScript, so maybe I'm doing this all wrong. I've tried numerous solutions online, however I had no luck. I would also like to avoid in-line JavaScript if possible, but I'm open to any solution at this point.

Upvotes: 0

Views: 251

Answers (1)

basic
basic

Reputation: 3408

As I mentioned in my comment, the way things are set up you are not actually firing your function when you click things. You call it after the function but that doesn't "watch" things.


You can resolve this in a few ways. The easiest would be (not changing to jquery or other and leaving your vanilla js alone) to simply apply an onclick to your radios.

Example:

 <input type="radio" onclick="changeTotebagColor()" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">

Upvotes: 1

Related Questions