In this case you should use radio instead of checkbox , because unlike checkbox only allows you to choose an option.
Create a label
for each image and add a radio input before the img
tag:
<label>
<input type="radio" name="icones" value="valor 1">
<img src="caminho_da_imagem_1">
</label>
<label>
<input type="radio" name="icones" value="valor 2">
<img src="caminho_da_imagem_2">
</label>
Note that radios must have the same name
, which changes is only the value
of each. It is this value
that will identify which image the user has chosen.
CSS
In CSS you will hide radio with opacity
, but when you click on the image, its radio will be checked by changing the border color of the adjacent image: / p>
/* oculta o radio */
input[name=icones]{
position: absolute;
opacity: 0;
}
/* propriedades da imagem */
input[name=icones] + img{
cursor: pointer;
border: 4px solid #000;
}
/* altera a cor da borda */
input[name=icones]:checked + img{
border-color: #30F519;
}
You can send the radio value checked via POST form to PHP and pick up with $_POST['icones']
(where icones
is name
of radios ).
Example: click on an image and then click the button to display the value of radio is checked:
function demo(){
var icones = document.querySelector("input[name=icones]:checked");
console.log("A imagem selecionada é a: " + icones.value);
}
input[name=icones]{
position: absolute;
opacity: 0;
}
input[name=icones] + img{
cursor: pointer;
border: 4px solid #000;
}
input[name=icones]:checked + img{
border-color: #30F519;
}
Selecione uma imagem:
<form method="post" action="pagina.php">
<div style="display: flex;">
<div>
<label>
<input type="radio" name="icones" value="1">
<img src="https://img.icons8.com/ultraviolet/2x/avatar.png"></label></div><div><label><inputtype="radio" name="icones" value="2">
<img src="https://img.icons8.com/ultraviolet/2x/avatar.png"></label></div><div><label><inputtype="radio" name="icones" value="3">
<img src="https://img.icons8.com/ultraviolet/2x/avatar.png"></label></div></div></form><buttononclick="demo()">Value da imagem selecionada</button>