I'm working on a movie selector project. I have five radio buttons, after a user has clicked on a radio button, I want to show the movies with that value. I'm thinking a switch statement works the best with this project. I can't seem to get it work, though.
This is one of the radio buttons:
<input type="radio" id="avenger-movies" name="select-movie" value="avenger-movies">
<label for="avenger-movies">Avenger films</label>
How do I write the statement for these buttons? This is my function thus far:
const getRadioButtons = document.getElementsByName("select-movie");
getRadioButtons.forEach((radiobtn) => {
radiobtn.addEventListener('change', (event) => {
function handleOnChangeEvent() {
// console.log(event.target.value)
const inputValue = event.target.value;
switch (inputValue) {
// Case..
}
}
handleOnChangeEvent()
})
})
CodePudding user response:
<div id="allRadio">
<input type="radio" id="avenger-movies" name="select-movie" value="avenger-movies">
<label for="avenger-movies">Avenger films</label>
<input type="radio" id="hello" name="select-movie" value="avenger-movies">
<label for="hello">hello world</label>
</div>
<script>
document.getElementById("allRadio").addEventListener("click",(e)=>{
switch(e.target.getAttribute("id")){
case 'avenger-movies':
alert(1);
break;
case 'hello':
alert(2);
break;
}
})
</script>
You can use event delegation to handle it, I hope it helps you.