如何在表单提交时,若多个div内select值重复则阻止提交
Solution Using jQuery
Definitely doable! Here's a modified version of your submit handler that checks for duplicate select values across your divs and blocks submission if duplicates are found:
$("form").submit(function(e) { // Object to keep track of how many times each select value appears const valueOccurrences = {}; let duplicatesFound = false; // Loop through every select element inside the form's divs $(this).find("div select").each(function() { const selectedValue = $(this).val(); // Optional: Skip empty values if you don't want to count unselected options if (selectedValue) { // Increment the count for this value valueOccurrences[selectedValue] = (valueOccurrences[selectedValue] || 0) + 1; // If we hit 2 occurrences, we know there's a duplicate—no need to check further if (valueOccurrences[selectedValue] >= 2) { duplicatesFound = true; return false; // Exit the loop early to save resources } } }); if (duplicatesFound) { alert("2 div or more have the same value, please change them"); e.preventDefault(); // Stop the form from submitting return false; } // If no duplicates, let the form submit normally return true; });
How this works:
- We create an object (
valueOccurrences) to track how many times each select value is chosen. - We loop through every
<select>inside your form's<div>elements. - For each selected value, we increment its count in the object. If any count hits 2 or more, we flag that duplicates exist and stop checking early.
- If duplicates are found, we show your alert and use
e.preventDefault()to block the form submission. - The optional check for
selectedValueskips empty (unselected) options—remove this if you want to treat empty values as duplicates too.
Just make sure your jQuery script is loaded properly (you already have the Google CDN link in your code, so that's covered!).
内容的提问来源于stack exchange,提问作者Nassim Nasri
相关产品推荐
相关产品推荐

