I have 3 checkboxes, and I need each one to change the background of a color. I get the first one to change color, but the others, I don't know how to refer to them, I tried with the queryselectorAll, but it doesn't work for me.
'use strict'
let box = document.querySelector('input[type=checkbox]');
function color(){
if(box.checked)
document.body.style.background='red';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="checkbox" value="red" onchange ="color()"/>Rojo
<input type="checkbox" value="blue" onchange ="color()"/>Azul
<input type="checkbox" value="gren" onchange ="color()"/>Verde
<script src="ejercicio4.js"></script>
</body>
</html>
What you should use for this is an input type
radio
, since when several radios have the samename
one you will not be able to select more than one at a time . If it is about changing the background color based on that criteria, it will be very complicated with the checkbox, since you could have several selected at the same time, having to resort to a supplementary procedure to make the checkbox behave as if it were a radio.If you use a radio the process is very simple. You wouldn't even have to use the
if
, you just get the value of the radius inside the function and change the background color based on it. That is all.Another thing, you had an error writing
gren
, it must begreen
.