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" class="sup-required"><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" class="button btnAction" 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>";
}
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 class="row-item">';
.... // 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 addeddiv
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.
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 "
I hope it helps.
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
JQuery is arguably the most popular JavaScript library with so many features for modern development. JQuery is a fast and concise JavaScript library created by John Resig in 2006. It is a cross-platform JavaScript library designed to simplify client-side HTML scripting. Over 19 million websites are currently using jQuery! Companies like WordPress, Facebook, Google, IBM and many more rely on jQuery to provide a kind of web browsing experience.
https://jquery.com/
HTML (English "hyper text markup language" - hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.