Hi Blake, I don't know if this can help you or at least give you an idea or a guide.
Try the following:
$(document).ready(function () {
// Define the table selector
var tableSelector = '#q4';
// Define the ID field selector pattern for all rows inside the table
var idFieldSelector = '[id^="Field1("]'; // Matches fields with IDs like q4(1), q4(2), etc.
function validateUniqueIDs() {
var ids = [];
var isUnique = true;
// Iterate over each ID field within the table
$(tableSelector).find(idFieldSelector).each(function () {
var idValue = $(this).val().trim();
if (idValue) {
if (ids.includes(idValue)) {
isUnique = false;
return false; // Stop the loop if a duplicate is found
}
ids.push(idValue);
}
});
return isUnique;
}
// Function to show an error alert and clear the duplicate value
function showErrorAndClear(field) {
alert("Each ID must be unique. Please enter a different value.");
field.val(''); // Clear the duplicate entry
}
// Validate on input in each ID field, including newly added rows
$(tableSelector).on('input', idFieldSelector, function () {
if (!validateUniqueIDs()) {
showErrorAndClear($(this));
}
});
// Validate on adding a new row
$(tableSelector).on('click', '.add-row-button', function () {
setTimeout(function () {
// Re-bind validation to the ID field in any new rows added
$(tableSelector).find(idFieldSelector).off('input').on('input', function () {
if (!validateUniqueIDs()) {
showErrorAndClear($(this));
}
});
}, 100); // Wait briefly to ensure the new row is in the DOM
});
});
Explanation:
- Selectors:
- tableSelector = '#q4': Targets the table with the ID q4. "You must replaced by your own tableSelector ID" in my test was q4.
- idFieldSelector = '[id^="Field1"]': Targets all fields inside the table whose IDs start with Field1, covering all rows like Field1(1), Field1(2), etc. "You must find and change according your ID field id Selector."
- Event Binding:
- Binds the validation function to any existing and newly added rows, ensuring that every time a value is entered in the Field1 ID field, it checks for duplicates across all rows.
This will now validate unique IDs in all Field1 fields within #q4, including any newly added rows. If a duplicate value is detected, the script displays an alert and clears the duplicated field.
The form I made to test this:
The form in preview:
That message popup when trying to duplicate ID number 2
I hope this helps you.