How to use svg (or div) to click and select the corresponding checkbox

1

I have a form that is a revenue search filter. In this filter I have a checkbox group for the category:

<form method="get" action="/busca">
  <h4>Categoria</h4>
  <input type="checkbox" name="categoria[]" value="entrada"> Entrada
  <input type="checkbox" name="categoria[]" value="principal"> Principal
  <button type="submit">Buscar Receitas</button>
</form>

I wanted instead to appear the checkboxes, an image (svg) to click, and clicking on the image it marks the corresponding checkbox. I am using fontawesome library. Then the DIV that wanted it to be clickable would look like this:

<div class="categoria" id="entrada">
  <i class="fas fa-apple"></i><br/>
  Entrada
</div>
<div class="categoria" id="principal">
  <i class="fas fa-utensils"></i><br/>
  Principal
</div>

Then when you click on the divs, it selects the corresponding checkbox.

And one more item, when I click on the div, it changes the css class, to turn red for example. You could add the class ".click" and click again, remove this class.

    
asked by anonymous 05.09.2018 / 16:12

1 answer

2

There's a way to do it, I'm going to use some concepts that @hugocsl used.

Each <div> must have its id and onclick to call the function, which will be sending a parameter, which is id . With the standardization of id of <button> , always starting with btn- , just concatenate the id sent with btn and trigger the checkbox markup trigger and insert a new style:

function trocar(id){
   $('#btn-' + id).trigger('click');
   $("#" + id + " i").closest( ".categoria" ).toggleClass("clicado")
}
.clicado{
  color: #ff0000;
}
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head><body><formmethod="get" action="/busca">
  <h4>Categoria</h4>
  <input type="checkbox" name="categoria[]" value="entrada" id="btn-entrada"> Entrada
  <input type="checkbox" name="categoria[]" value="principal" id="btn-principal"> Principal
  <input type="checkbox" name="categoria[]" value="sobremesa" id="btn-sobremesa"> Sobremesa
  <button type="submit">Buscar Receitas</button>
</form>
<div class="categoria" id="entrada" onclick="trocar(this.id)">
  <i class="fab fa-apple fa-2x"></i><br/>
  Entrada
</div>

<div class="categoria" id="principal" onclick="trocar(this.id)">
  <i class="fas fa-utensils fa-2x"></i><br/>
  Principal
</div>

<div class="categoria" id="sobremesa" onclick="trocar(this.id)">
  <i class="fas fa-cookie fa-2x"></i><br/>
  Sobremesa
</div>
</body>
</html>
    
05.09.2018 / 16:42