To achieve dynamic updates of the second input or select element based on the user's selection in the first input/select, and ensure that all data is correctly captured before sending the request, follow the steps below. This approach will enhance the interactivity and reliability of your form.
1. Identify the Dependent Elements
From your HTML structure, it appears that there are two primary areas where dependencies may exist:
-
Recipient Selection:
- Phone Number Input (
#phoneNum)
- Session Selection (
#customersId)
-
Sender Selection:
- Group Selection (
#group_select)
Assuming that selecting a Session should dynamically update the Sender's Phone Number or Group, we'll implement dependencies accordingly.
2. Update the HTML Structure (If Necessary)
Ensure that each select/input element has unique IDs and is structured to allow dynamic updating. From your provided code, it looks well-structured. However, ensure that the elements you want to update dynamically are properly referenced.
3. Implement JavaScript for Dynamic Updates
We'll add event listeners to capture changes in the first select/input and update the second select/input accordingly. Here's how you can modify your JavaScript to achieve this:
<!-- Add this script after your existing JavaScript includes -->
<script>
document.addEventListener('DOMContentLoaded', function() {
// Data object to hold form data
var data = {
toPhone: '', // Recipient's phone number (from phoneNum input)
phone: '', // Sender's phone number (from customersId select)
msg: '', // Message content
groupId: '', // Selected group ID
};
// Handle Send Message Form Submission
const sendMessageBtn = document.getElementById('submitSendMessageBtn');
const confirmationModal = document.getElementById('confirmationModal');
const closeModals = document.querySelectorAll('.custom-modal .close, .btn-close-modal');
sendMessageBtn.addEventListener('click', function() {
if (!data.toPhone || !data.msg || !data.phone || !data.groupId) { // Ensure all required fields are filled
alert("يرجى ملء جميع الحقول المطلوبة.");
return;
}
// Show the confirmation modal
confirmationModal.style.display = 'block';
document.body.classList.add('modal-open');
});
// Close all modals when close button or cancel button is clicked
closeModals.forEach(function(element) {
element.addEventListener('click', function() {
document.querySelectorAll('.custom-modal').forEach(function(modal) {
modal.style.display = 'none';
});
document.body.classList.remove('modal-open');
});
});
// Handle Confirm Send Message
const confirmSendMessageBtn = document.getElementById('confirmSendMessage');
confirmSendMessageBtn.addEventListener('click', function() {
confirmationModal.style.display = 'none';
document.body.classList.remove('modal-open');
sendMessage();
});
function sendMessage() {
var sendmsg = {
'toPhone': data.toPhone, // Recipient's phone number
'phone': data.phone, // Sender's phone number
'msg': data.msg,
'groupId': data.groupId
};
console.log('Sending Message:', sendmsg); // Debugging line
fetch('send-message-group', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify(sendmsg)
})
.then(response => response.json().then(body => ({ status: response.status, body: body })))
.then(({status, body}) => {
if (status >= 200 && status < 300 && body.success) {
console.log('SendMessageGroup Success:', body);
alert('تم ارسال الرسالة بنجاح.');
// Proceed with post-data-message-grp fetch
return fetch("/post-data-message-grp", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
},
body: JSON.stringify(data)
});
} else {
console.error('SendMessageGroup Error:', body);
const errorMessage = body.message || 'حدث خطأ غير متوقع.';
const errorDetails = body.error ? JSON.stringify(body.error) : '';
alert(`فشل في ارسال الرسالة. ${errorMessage} ${errorDetails}`);
throw new Error('SendMessageGroup failed');
}
})
.then(response => response.json())
.then(responseData => {
console.log('Post-data-message-grp Success:', responseData);
alert('تم تحديث الرسائل بنجاح.');
})
.catch(error => {
console.error('Error:', error);
alert('حدث خطأ أثناء ارسال الرسالة.');
});
}
// Handle input changes
const phonenumInput = document.getElementById('phoneNum'); // Upper input for toPhone
const msgInput = document.getElementById('ae');
const groupSelect = document.getElementById('group_select_modal');
phonenumInput.addEventListener('input', function(event) {
data.toPhone = event.target.value;
console.log('Recipient Phone number:', event.target.value);
});
msgInput.addEventListener('input', function(event) {
data.msg = event.target.value;
console.log('Message:', event.target.value);
});
groupSelect.addEventListener('change', function(event) {
data.groupId = event.target.value;
console.log('Selected Group ID:', event.target.value);
});
// Handle select change for sender's phone
const customersSelect = document.getElementById('customersId');
customersSelect.addEventListener('change', function() {
const selectedOption = this.options[this.selectedIndex];
data.phone = selectedOption.value.trim(); // Sender's phone number from dropdown
console.log('Sender Phone:', data.phone);
});
// Handle modal buttons for Adding Phone
const addPhoneModal = document.getElementById('addPhoneModal');
const submitAddPhoneBtn = document.getElementById('submitAddPhoneBtn');
submitAddPhoneBtn.addEventListener('click', function() {
const phoneNumber = document.getElementById('phonenum').value.trim();
if (!phoneNumber) {
alert("يرجى إدخال رقم الهاتف.");
return;
}
// Implement AJAX request to add phone if necessary
console.log('Adding Phone Number:', phoneNumber);
// Close the modal
addPhoneModal.style.display = 'none';
document.body.classList.remove('modal-open');
// Optionally reset the form
addPhoneModal.querySelector('form').reset();
// Optionally, update the customersId select with the new phone number
const newOption = document.createElement('option');
newOption.value = phoneNumber;
newOption.text = phoneNumber;
customersSelect.add(newOption);
});
// Handle modal buttons for Selecting Group
const selectGroupModal = document.getElementById('selectGroupModal');
const submitSelectGroupBtn = document.getElementById('submitSelectGroupBtn');
submitSelectGroupBtn.addEventListener('click', function() {
const selectedGroup = document.getElementById('group_select_modal').value;
if (!selectedGroup || selectedGroup === 'default') {
alert("يرجى اختيار مجموعة.");
return;
}
// Implement AJAX request to select group if necessary
console.log('Selected Group ID:', selectedGroup);
// Close the modal
selectGroupModal.style.display = 'none';
document.body.classList.remove('modal-open');
// Optionally, update related fields based on the selected group
updateRelatedFields(selectedGroup);
});
// Function to update related fields based on selected group
function updateRelatedFields(groupId) {
// Example: Update the sender's phone number based on the group
// This requires fetching data from the server or having a predefined mapping
// For demonstration, let's assume a simple mapping
const groupPhoneMapping = {
'1': '1234567890',
'2': '0987654321',
// Add more mappings as needed
};
if (groupPhoneMapping[groupId]) {
data.phone = groupPhoneMapping[groupId];
customersSelect.value = groupPhoneMapping[groupId];
console.log('Updated Sender Phone based on Group:', data.phone);
} else {
// Handle cases where the group ID does not have a predefined phone
data.phone = '';
customersSelect.value = '';
console.log('No Sender Phone mapped for Group:', groupId);
}
}
// Prevent interaction with background when modal is open
window.onclick = function(event) {
document.querySelectorAll('.custom-modal').forEach(function(modal) {
if (event.target == modal) {
modal.style.display = "none";
document.body.classList.remove('modal-open');
}
});
}
// Initialize DataTable
$(document).ready(function() {
$("#table").DataTable({
pagingType: "full_numbers",
scrollX: true,
autoWidth: false,
});
});
// Additional functionality for checkboxes if needed
const checkboxes = document.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach((checkbox) => {
checkbox.addEventListener('change', function() {
if (this.checked) {
const row = this.closest('tr');
// Ensure your table has at least 3 columns
const phoneCell = row.cells[2]; // Adjust index as per your table's column
if (phoneCell) {
const phone = phoneCell.textContent.trim();
data.toPhone = phone;
console.log('Selected Phone from Table:', phone);
// Optionally, uncheck other checkboxes if only one selection is allowed
checkboxes.forEach(cb => {
if (cb !== this) cb.checked = false;
});
}
}
});
});
// Function to dynamically update the second input/select based on the first selection
// Example: When a session is selected, update the available groups
customersSelect.addEventListener('change', function() {
const selectedSession = this.value;
updateGroupsBasedOnSession(selectedSession);
});
function updateGroupsBasedOnSession(sessionId) {
// Fetch groups related to the selected session via AJAX
// For demonstration, let's assume we have a mapping
const sessionGroupMapping = {
'session1': [
{ id: '1', name: 'Group A' },
{ id: '2', name: 'Group B' }
],
'session2': [
{ id: '3', name: 'Group C' },
{ id: '4', name: 'Group D' }
],
// Add more mappings as needed
};
const groupSelectElement = document.getElementById('group_select_modal');
groupSelectElement.innerHTML = ''; // Clear existing options
if (sessionGroupMapping[sessionId]) {
// Populate the group select with new options
sessionGroupMapping[sessionId].forEach(function(group) {
const option = document.createElement('option');
option.value = group.id;
option.text = group.name;
groupSelectElement.add(option);
});
} else {
// If no groups are mapped to the session, add a default option
const defaultOption = document.createElement('option');
defaultOption.value = 'default';
defaultOption.text = 'اختر مجموعة';
groupSelectElement.add(defaultOption);
}
}
});
</script>
4. Explanation of JavaScript Enhancements
-
Validation Enhancements:
- In the
sendMessageBtn click event, ensured that data.groupId is also checked to prevent incomplete submissions.
-
Dynamic Group Updating:
updateGroupsBasedOnSession Function: This function updates the Group Selection (#group_select_modal) based on the selected Session (#customersId). You can modify the sessionGroupMapping object or fetch this data from the server dynamically via AJAX if you have a large set of sessions and groups.
- Event Listener on
#customersId: When a session is selected, this listener calls updateGroupsBasedOnSession to refresh the groups accordingly.
-
Dynamic Sender's Phone Based on Group:
updateRelatedFields Function: This function updates the sender's phone (data.phone) based on the selected group. Modify the groupPhoneMapping object to match your actual data or fetch it dynamically.
-
Adding Phone Numbers:
- When a new phone number is added via the Add Phone Modal, it not only closes the modal but also adds the new phone number to the Sender's Phone Selection (
#customersId) dynamically.
-
Preventing Background Interaction:
- Ensured that clicking outside the modal or on the close buttons properly closes the modal and restores background scrolling.
-
Checkbox Handling:
- If you have checkboxes for selecting phone numbers from a table, the selected phone number is now stored in
data.toPhone and ensures only one checkbox can be selected at a time.
-
Initialization of DataTable:
- Ensured that the DataTable initializes correctly to enhance table interactions.
5. Server-Side Adjustments
Ensure your server-side logic can handle the dynamic data being sent from the client. Specifically:
- Endpoint
/send-message-group: Should accept and process toPhone, phone, msg, and groupId.
- Endpoint
/post-data-message-grp: Should handle the complete data object as needed.
- Session and Group Mappings: If you're dynamically mapping sessions to groups, consider creating an API endpoint to fetch groups based on the selected session to replace the hardcoded
sessionGroupMapping in the JavaScript.
6. Enhancements and Best Practices
-
Use const and let Instead of var: Modern JavaScript best practices recommend using const for variables that won't be reassigned and let for those that will. This helps prevent unexpected behaviors.
-
Modularize JavaScript Code: For better maintainability, consider breaking down your JavaScript into smaller modules or functions, especially if the application grows in complexity.
-
Error Handling: Implement more robust error handling and possibly user-friendly error messages based on server-side validations.
-
Accessibility Considerations:
- Ensure that modals are accessible via keyboard navigation.
- Use
aria attributes to enhance accessibility for screen readers.
-
Security Considerations:
- Validate all input data on the server-side to prevent malicious data submission.
- Ensure CSRF tokens are correctly implemented to protect against CSRF attacks.
7. Final Notes
The provided JavaScript enhancements ensure that your form dynamically updates based on user selections and that all data is correctly captured before sending the request. Adjust the mappings and data-fetching logic based on your actual data sources and business logic.
Feel free to further customize the modals, form validations, and dynamic updates to suit your specific requirements.