JS to style radio button list
anderu
Posted on December 31, 2023
Today I learn to create meme picker from Scrimba. User can pick a cat emotion from the 'select your current emotion' list and optional choose 'animated GIFs only' then a random cat meme will show up.
The part I want to highlight from this tutorial is where it style the radio button with the use of 'change' event and
getElementsByClassName
.
emotionRadios.addEventListener('change', highlightCheckedOption)
function highlightCheckedOption(e){
const radios = document.getElementsByClassName('radio')
for (let radio of radios){
radio.classList.remove('highlight')
}
document.getElementById(e.target.id).parentElement.classList.add('highlight')
}
First, the 'emotionRadios' div which hold all radios button list
addEventListener
for 'change'.Then we select all radio button with
document.getElementsByClassName('radio')
which provide list of array of radio button.for of
method use to loop thru the radio button and removeclass
of 'highlight'.
radioItems += `
<div class="radio">
<label for="${emotion}">${emotion}</label>
<input
type="radio"
id="${emotion}"
value="${emotion}"
name="emotions"
>
</div>`
- Above show the radio button HTML code to create a radio button. When the radio button is click, we want to add
class
of 'highlight' to the 'radio' div. So we usedocument.getElementById(e.target.id).parentElement.classList.add('highlight')
.
function getMatchingCatsArray(){
if(document.querySelector('input[type="radio"]:checked')){
const selectedEmotion = document.querySelector('input[type="radio"]:checked').value
const isGif = gifsOnlyOption.checked
const matchingCatsArray = catsData.filter(function(cat){
if(isGif){
return cat.emotionTags.includes(selectedEmotion) && cat.isGif
}
else{
return cat.emotionTags.includes(selectedEmotion)
}
})
return matchingCatsArray
}
}
Beside this, the tutorial also show the use of powerful
querySelector
which can be to use to select#id
,.class
and 'element' likeconst selectedEmotion = document.querySelector('input[type="radio"]:checked').value
.filter
andincludes
method is useful to filter the data and loop thru the array of object and thenincludes
will check the exact value in the list of item or object value and lastly provide the match value object list only.
Eat, sleep, code, repeat!
Andrew Tan
Posted on December 31, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.