I’m trying to get the values of the checkboxes I check and put them in a php variable, but when I output that value, it gives me zeroes (0). If I check 3 boxes, I get three zeroes, etc. Info: I want every checkbox that is checked, so if cb1 and cb3 are checked, I want the variable to be “cb1cb3”
HTML code:
<div class="form-label-group"> <h2 for="checkboxes"> Some text </h2> <input type="checkbox" id="cb1" onclick="click()" name="cb[]" value="cb1"><label for="cb1">cb1</label><br> <input type="checkbox" id="cb2" onclick="click()" name="cb[]" value="cb2"><label for="cb2">cb2</label><br> <input type="checkbox" id="cb3" onclick="click()" name="cb[]" value="cb3"><label for="cb3">cb3</label><br> </div>
JS/php code:
function click(){ $("input[name='cb[]']:checked").each(function () { cb+=$(this).text(); //also tried to put a $ sign in front of the cb variable: $cb+=$(this).text(); //and with val instead of text: $cb+=$(this).val(); i++; }); }
Hope you can help out
Advertisement
Answer
Always good practice to keep your JS and HTML separate by not using inline JS. Also I would use the change
event and .map()
method as follows:
$('input[name="cb[]"]').on('change', function() { const checkedVals = $('input[name="cb[]"]:checked').map((i,c) => c.value).get(); console.log( checkedVals ); //array console.log( checkedVals.join('') ); //strings: values concatenated });
DEMO
$(function() { $('input[name="cb[]"]').on('change', function() { const checkedVals = $('input[name="cb[]"]:checked').map((i,c) => c.value).get(); console.log( checkedVals ); console.log( checkedVals.join('') ); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-label-group"> <h2 for="checkboxes"> Some text </h2> <input type="checkbox" id="cb1" name="cb[]" value="cb1"><label for="cb1">cb1</label><br> <input type="checkbox" id="cb2" name="cb[]" value="cb2"><label for="cb2">cb2</label><br> <input type="checkbox" id="cb3" name="cb[]" value="cb3"><label for="cb3">cb3</label><br> </div>