Passing Parameters from Several Checkboxes to a Jquery Variable

1
Hello, I would like to know how I get the value field values from several selected checkboxes and save them to a jquery variable separated by commas, but without using the id field, since it is already being used in a label .

    
asked by anonymous 07.10.2016 / 23:15

2 answers

3

You can simply use $(':checked') as a selector or be more explicit and use $('input[type=checkbox]:checked') .

To pass to an array you can use .get() combined with .map() that converts a jQuery collection to a native array and then fetches value to each element / object in that array. To pass to string (I think that's what you want) just do .toString() or .join(',');

var valores = $(':checked').get().map(el => el.value).join(',');
console.log(valores);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="checkbox" value="a">
<input type="checkbox" value="b">
<input type="checkbox" value="c" checked="true">
<input type="checkbox" value="d" checked ="true">
    
07.10.2016 / 23:18
1

You have several ways of working this.

To get the check box value you can do the following

$("input[type='checkbox']").val();

or if you set a class or id that way

$('#check_id').val();
$('.check_class').val();

However, this will return the same value if it is checked or not, this can be confusing as it is different from the displayed form behavior. check if it is checked or not you use the following form:

if ($('#check_id').is(":checked"))
{
  // it is checked
}

In your case, this function should solve

 $(".checkboxClass").click(function(){
  var selectedCountry = new Array();
  $(".checkboxClass:checked").each(function(){

    selectedCountry.push($(this).val());
  });
  $(".exibirSelecao").html(selectedCountry.join('<br>'));
});

You should by the class .checkboxClass in all checkbos you want to get the value

create a div with class displaySelection

    
07.10.2016 / 23:21