I am trying to create an array combining both the label and value of an input field. The problem is my jQuery code combines ALL labels and input values, not just those which are selected. The code I am trying is as below:
jQuery:
let values = [];
$("label[for='servicelist-label[]'], input[name='servicelist-details[]']").each(function() {
values.push($(this).text());
values.push($(this).val());
});
PHP Implode Code:
$serviceinfo = implode("",array_map(function($i){
return implode("<br>",$i);
},array_chunk($_POST['servicelist'],2)));
PHP Form Elements:
<label for="servicelistlabel[]" >Service 1: </label><input class="list" type="checkbox" name="servicelistcheckbox[]" id="servicelist1" value="Area 1"><br>
<label for="servicelistlabel[]" >Service 2: </label><input class="list" type="checkbox" name="servicelistcheckbox[]" id="servicelist2" value="Area 2"><br>
<label for="servicelistlabel[]" >Service 3: </label><input class="list" type="checkbox" name="servicelistcheckbox[]" id="servicelist3" value="Area 3"><br>
Any help would be much appreciated! Thank you.
2
Answers
@clash was on the right track with the fact I needed to switch the implode separators. In the end my array_chunk needed to have the value of 4 and the line breaks needed to be in different locations in order for it to work. Here is the working code for anyone else with a similar problem:
EDIT: As pointed out by @clash, my implode code will not work in PHP8. It looks like my array is incorrect. Basically I am trying to include both the label AND checkbox value in the array, however all of the labels are being added regardless of whether the checkbox is checked or not.
This is a jQuery problem I do not know how to solve. The code used is below:
PHP Form Elements:
jQuery:
PHP Implode Function (incorrect):
You are so close, you just need to switch the implode-separators:
This should result in the desired output.
Edit:
Ok I now know what you want to achieve. There are a couple of problems with the JS part. I will go over your code real quick
$(this)
is the label at one iteration, the checkbox in the next iteration.$(this).val()
is empty the first iteration since the label has no value.$(this).text()
is empty the next iteration since the checkbox has no text.["Label", "", "", "Value"]
for each checkbox you have checked.for=""
attribute in a label has to match theid=""
attribute of the checkbox, or else the label will not trigger on click.How to solve?
https://jsfiddle.net/5ubnes1k/
Take a look at this fiddle.
I put each label/checkbox-combo into a
div.checkbox
to have an easier time selecting it.Now we only iterate over the
.checkbox
divs, selecting the label and checkbox inside. If the checkbox is checked, we push the label-text and checkbox-value into the array. The output is something like:["Service 1: ", "Service1", "Service 3: ", "Service3"]
With this array structure you should be able to get the wanted result with the
implode
part of your code.