Select an image among other images

Asked

Viewed 66 times

1

I need to make an image "gallery" and pass some identification value, in PHP, showing which image I selected. The idea is to show several images, as if they were icons, and the user choose the preferred one. I think you can do using checkbox, but I don’t know how you do it.

Below an example: Various icons, selectable, properly identified...

inserir a descrição da imagem aqui

1 answer

0


In this case you should use radio instead of checkbox, because unlike the checkbox, the radio only allows you to choose an option.

Create a label for each image and add before the tag img an input of the type radio:

<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 the radios must have the same name, what changes is only the value of each. It’s this value which will identify which image the user has chosen.

CSS

In CSS you will hide the radio with opacity, but by clicking on the image, its respective radio will be checked by changing the color of the adjacent image border:

/* 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 value of radio checked via POST form for PHP and pick up with $_POST['icones'] (where icones is the name of radios).

Example: click on an image and then click on the button to display the value of which radio is checked out:

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>
            <input type="radio" name="icones" value="2">
            <img src="https://img.icons8.com/ultraviolet/2x/avatar.png">
         </label>
      </div>
      <div>
         <label>
            <input type="radio" name="icones" value="3">
            <img src="https://img.icons8.com/ultraviolet/2x/avatar.png">
         </label>
      </div>
   </div>
</form>
<button onclick="demo()">Value da imagem selecionada</button>

  • Perfect! That’s right, thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.