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.
Aucun commentaire:
Enregistrer un commentaire