List value of checkbox items

Asked

Viewed 121 times

4

How do I make list the checkbox values when the user select and when you are unselected the value does not appear in the list?

<select class="form-control" id="list-lugar">
  <option value="0" disabled="true" selected="true">-</option>
  <option value="200">1 Shopping</option>
  <option value="200">2 Shopping</option>
  <option value="100">3 Shopping</option>
  <option value="100">4 Plaza</option>
  <option value="100">5 Shopping</option>
  <option value="100">6 Plaza</option>
</select><br><br>

<input id="add-buffet" type="checkbox" value="1000" />
<label>Buffet</label><br>
<input id="add-decoracao" type="checkbox" value="499" />
<label>Decoração</label><br>
<input id="add-foto" type="checkbox" value="800" />
<label>Foto</label><br><br>

<label>Lista</label><br><br>
item 1 R$200,00<br>
item 2 R$1.000,00<br>
item 3 R$499,00<br>
item 4 R$800,00<br>

3 answers

2

You can use the following selector to pick all checkboxes that are selected:

$('input[type="checkbox"]:checked')

Below is an example with your code. By clicking on the checkbox, it selects/deselects and lists all the ones that are selected.

// click nos checkbox
$('input[type="checkbox"]').click(function() {
  console.log("\n");
  // seleciona todos checkboxes checados
  $('input[type="checkbox"]:checked').each(function() {
    // escreve no console
    console.log($(this).val() + ' ');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="list-lugar">
  <option value="0" disabled="true" selected="true">-</option>
  <option value="200">1 Shopping</option>
  <option value="200">2 Shopping</option>
  <option value="100">3 Shopping</option>
  <option value="100">4 Plaza</option>
  <option value="100">5 Shopping</option>
  <option value="100">6 Plaza</option>
</select><br><br>

<input id="add-buffet" type="checkbox" value="1000" />
<label>Buffet</label><br>
<input id="add-decoracao" type="checkbox" value="499" />
<label>Decoração</label><br>
<input id="add-foto" type="checkbox" value="800" />
<label>Foto</label><br><br>

<label>Lista</label><br><br>
item 1 R$200,00<br>
item 2 R$1.000,00<br>
item 3 R$499,00<br>
item 4 R$800,00<br>

From here you can do whatever you want with the selected values, only change the code within the each

  • Got it!! Sorry the question, I don’t know any javascript, and to take the value of options and checkbox and present in a div for example? It’s easy to do that?

  • You may ask, we participate here to help us... before the each, creates a variable, resultadofor example... then creates the div with id='resultado' for example.. in the code I put in place of the console.log you can accumulate the values in a variable, thus: resultado += "Valor: " + $(this).val() + "<br /">; After the each only play the variable on div: $('#resultado').html(resultado); and will appear the values selected in div

2


Guy made an example here looking like what you want, showing and hiding the choices made by the user:

$(document).ready(function() {
  $('input[type="checkbox"]').click(function() {
    var inputs = $(this);
    var valor = $(this).val();
    var label = $("label[for='" + $(this).attr('id') + "']").text();
  
      if(inputs.is(":checked") == true) {
        $("#lista").append("<span id='span'> - " + label + " : " + valor + "</span>" );
      } else {
          $("#span").remove();
      }
  });
  $("select").on("change", function() {
    var str = "";
    $("select option:selected").each(function() {	
      str += $(this).text();
    });
    $("#spanSelect").text(str);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="list-lugar">
  <option value="0" disabled="true" selected="true">-</option>
  <option value="200">1 Shopping</option>
  <option value="200">2 Shopping</option>
  <option value="100">3 Shopping</option>
  <option value="100">4 Plaza</option>
  <option value="100">5 Shopping</option>
  <option value="100">6 Plaza</option>
</select><br><br>

<input id="add-buffet" type="checkbox" value="1000" />
<label for="add-buffet">Buffet</label><br>
<input id="add-decoracao" type="checkbox" value="499" />
<label for="add-decoracao">Decoração</label><br>
<input id="add-foto" type="checkbox" value="800" />
<label for="add-foto">Foto</label><br><br>

<label id="lista">Lista</label><br><br>
<span id="spanSelect"></span><br><br>
item 1 R$200,00<br>
item 2 R$1.000,00<br>
item 3 R$499,00<br>
item 4 R$800,00<br>

  • That’s what I was trying to do, but I wasn’t returning anything, thank you very much!

  • Nothing, man. Nice of you to help!

  • Leandro, a doubt, as I do to include in the list the item name, for example name="Cushion" so in the list would be Cushion - R$800

  • This way the code is not able to connect each label with the selected inputs. What you can do and solve is to put the description type pillow within the input value in Html.

  • then but when I put string inside value, when I add all error values

  • Okay, I get it, man. Hang on a second, I got it, I’m out, but I can get a computer to fix it ;)

  • Oops, I was just leaving, but, I came back quickly. I’m going to review the code here and put the resolution just a moment.

  • My only difficulty now is this, put string before value, to be able to add all values without error :)

  • Blza man! Working.

Show 5 more comments

0

Follow an alternative with the Vanillajs (Javascript Pure)

/* Captura todos os elementos do tipo checkbox */
const cb = document.querySelectorAll("input[type=\"checkbox\"]")

/* Adiciona o evento "analyzeCheckBox" no elemento */
cb.forEach( checkbox => {
  checkbox.addEventListener("change", analyzeCheckBox)
})

/* Função para verificar quais checkbox estão marcados */
function analyzeCheckBox() {

  /* Limpa o console */
  console.clear()
  
  cb.forEach( checkbox => {
  
    let text = ` ${checkbox.nextElementSibling.textContent}, cujo valor é ${checkbox.getAttribute("value")}, está `
  
    /* Verifica se o elemento está marcado */
    if (checkbox.checked) {
      console.log(text, "marcado")
    } else {
      console.log(text, "desmarcado")
    }
  })
}
<input id="add-buffet" type="checkbox" value="1000" />
<label>Buffet</label><br>
<input id="add-decoracao" type="checkbox" value="499" />
<label>Decoração</label><br>
<input id="add-foto" type="checkbox" value="800" />
<label>Foto</label><br><br>

Browser other questions tagged

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