Home > Software design >  jQuery If checkbox in foreach loop is checked, include checkboxes and input values within that loop
jQuery If checkbox in foreach loop is checked, include checkboxes and input values within that loop

Time:09-26

I am creating a php email form with a foreach loop which creates a checkbox with several other checkboxes and input fields within the foreach loop. The loop might repeat several times, creating several sets of checkboxes, however I only want to include the checked checkbox and associated fields, not all of those within every loop. Only those selected would then be included in the 'servicelist' array and email.php.

My code below is incorrect as it is gathering all of the data from every loop. I understand this is because the input fields are populated with data, so the data is added to the array.

I think I need to add an 'if' statement to my jQuery, but I'm not sure how? I have tried changing the jQuery line 'if (checkbox.is(":checked"))' with the below line of code without success.

if ($("input[data-name='servicetitle[]'").prop(":checked")) {

PHP Form:

foreach ( $order->get_items() as $item_id => $item ) {

         // Main checkbox to check if selected
         echo '<div data-name="sup-checkbox-title[]">';
         echo '<label for="servicetitle">Service:</label><br>';
         echo '<input type="checkbox" id="servicetitle" data-name="servicetitle[]" value="' . $item->get_name() . '"><span>' . $item->get_name() .'</span><br>';
         echo '</div><br>';

         // Sub checkboxes and input fields to include in array if above checkbox checked
         echo '<div data-name="sup-input[]"><br>';
         echo '<label for="weightallowance">Weight Allowance Per Bin:</label><br>';
         echo '<input type="text" id="weightallowance" value="Weight1" ><br>';
         echo '</div><br>';

         echo '<div data-name="sup-input-date[]">';
         echo '<label for="servicestartdate">Service Start Date:</label><br>';
         echo '<input type="date" id="servicestartdate" ><br>';
         echo '</div><br>';

         echo '<div data-name="sup-checkbox[]">';
         echo '<label for="routenumberAln1">Route Number:</label><br>';
         echo '<input type="checkbox" id="routenumberAln1" value="Aln1" >Aln1<br>';
         echo '</div><br>';

         echo '<div data-name="sup-input-costs[]">';
         echo '<label for="supplierpriceperlift">Supplier Price Per Lift:</label><br>';
         echo '<input type="text" id="supplierpriceperlift" value="£16.75"><br>';
         echo '</div><br>';      

}

echo '<div name="submit"  onClick="sendSupplierForm();">Send Email</div>';
                

jQuery:

function sendSupplierForm() {

let values = [];
    
$("div[data-name='sup-checkbox-title[]'], div[data-name='sup-input[]'], div[data-name='sup-input-date[]'], div[data-name='sup-checkbox[]'], div[data-name='sup-input-costs[]']").each(function() {
            
     const label = $(this).find('label');
     const checkbox = $(this).find('input[type="checkbox"]');
     const input = $(this).find('input[type="text"]');
     const date = $(this).find('input[type="date"]');
            
     if (checkbox.is(":checked")) {
        values.push(label.html(), checkbox.val());
     }
            
     if (input.val()) {
        values.push(label.html(), input.val());
     }
                    
     if (date.val()) {
        values.push(label.html(), date.val());
     }
                    
});

var data = {
     servicelist: values,
};

        jQuery.ajax({
        url: "email.php",
        data: data,
        dataType:'text',
        type: "POST",
        success:function(data){
        $("#EmailStatus").html(data);
        },
        error:function (){}
        });
}

email.php

$mailto = "info@******.com";
$subject = "Test";
$headers = "From: info@******.com\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";

$serviceinfo = implode("<br>",array_map(function($i){
               return implode(" ",$i);
               },array_chunk($_POST['servicelist'],2)));

$message = "
<html>
<head>
  <title>Form Details</title>
</head>
<body>
  <p>" . $serviceinfo . "</p>
</body>
</html>
";

// PHP MAILER FUNCTION
$result1 = mail($mailto, $subject, $message, $headers);

// PHP MAILER MESSAGE
if ($result1) {
print "<div id='EmailStatusSuccess'>SUCCESS!!! The details have been sent.</div><br>";
} else {
print "<div id='EmailStatusFail'>ERROR... Sorry there is a problem sending the details. Please check and retry.</div><br>";
}

CodePudding user response:

I would suggest having unique IDs for your inputs. But with small adaptation to your code you can achieve what you want. Even though would be nice to know what your end goal is so we could guide you to a better solution.

to begin with you can wrap each group of inputs under a single <div> let's call it <div class='row-item'>

foreach ( $order->get_items() as $item_id => $item ) {
   echo '<div >';
   .... // rest of the code
   echo '</div>';
}

then you could use a similar to this jQuery code

let values = [];
$(".row-item").each(function() {
const checkbox = $(this).find('input[type="checkbox"]');
if (!checkbox.is(":checked")) {
    return;
}

$(this).find("div").each(function(){
    const val = $(this).find("input").val();
  if (!val){
    return;
  }
    values.push($(this).find("label").html(), val);
}); 

what does this code do?

It loops through the newly added div then find the checkbox in that div and skips the processing if the checkbox is not checked.

Then I noticed that what you tried to do is to basically push in an array the combination of label and value. So you could simply go through each <div> element under the .row-item and add the label and val combinations.

I also created a small example for you in JSFiddle that has hardcoded the HTML instead of the PHP code.

https://jsfiddle.net/yjLqseax/5/

CodePudding user response:

You must utilize the unique id of each item. Below is the code (I used test data):

<?php

    $data = array(
                1 => array(
                    'name' => 'Jack'
                ),
                2 => array(
                    'name' => 'John'
                ),
                3 => array(
                    'name' => 'Josh'
                ),
            );

    foreach ( $data as $item_id => $item ) {

        echo "-----------------------------------------------------------------";

        // set the id of this item
        echo '<div data-name="sup-checkbox-ids[]">';
        echo '<input type="hidden" name="item_id" value="'.$item_id.'" >';
        echo '</div>';

        // Main checkbox to check if selected
        echo '<div data-name="sup-checkbox-title[]">';
        echo '<label for="servicetitle">Service:</label><br>';
        echo '<input type="checkbox" id="servicetitle_'.$item_id.'" data-name="servicetitle[]" value="' . $item['name'] . '"><span>' . $item['name'] .'</span><br>';
        echo '</div><br>';

        // Sub checkboxes and input fields to include in array if above checkbox checked
        echo '<div data-name="sup-input[]"><br>';
        echo '<label for="weightallowance">Weight Allowance Per Bin:</label><br>';
        echo '<input type="text" id="weightallowance" value="Weight1" ><br>';
        echo '</div><br>';

        echo '<div data-name="sup-input-date[]">';
        echo '<label for="servicestartdate">Service Start Date:</label><br>';
        echo '<input type="date" id="servicestartdate" ><br>';
        echo '</div><br>';

        echo '<div data-name="sup-checkbox[]">';
        echo '<label for="routenumberAln1">Route Number:</label><br>';
        echo '<input type="checkbox" id="routenumberAln1" value="Aln1" >Aln1<br>';
        echo '</div><br>';

        echo '<div data-name="sup-input-costs[]">';
        echo '<label for="supplierpriceperlift">Supplier Price Per Lift:</label><br>';
        echo '<input type="text" id="supplierpriceperlift" value="£16.75"><br>';
        echo '</div><br>';

    }

?>

<button id="select_values">Select values<button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script>

    let values = [];

    $("#select_values").click(function(){

        var current_id = 0

        $("div[data-name='sup-checkbox-ids[]'], div[data-name='sup-checkbox-title[]'], div[data-name='sup-input[]'], div[data-name='sup-input-date[]'], div[data-name='sup-checkbox[]'], div[data-name='sup-input-costs[]']").each(function() {

            const id = $(this).find('input[name="item_id"]');
            const label = $(this).find('label');
            const checkbox = $(this).find('input[type="checkbox"]');
            const input = $(this).find('input[type="text"]');
            const date = $(this).find('input[type="date"]');

            if(id.val()){
                console.log('Current id is:' id.val());
                current_id = id.val();
            }

            if($('#servicetitle_' current_id).is(':checked')){

                if (checkbox.is(":checked")) {
                    values.push(label.html(), checkbox.val());
                }

                if (input.val()) {
                    values.push(label.html(), input.val());
                }

                if (date.val()) {
                   values.push(label.html(), date.val());
                }
            }

        });

        console.log(values); // Print the selected values, based upon the checkbox

        values = []; // empty values
    })


</script>

I hope it helps.

  • Related