如何用querySelectorAll获取名称含dropDown的下拉框选中值并展示
Alright, let's get this sorted out for you. Your current code has a few small issues that are keeping it from working correctly—let's break them down and fix them step by step.
First, fix the selector to target all your dropdowns
Your existing selector select[name="dropDown"] only looks for elements where the name attribute is exactly "dropDown", but your dropdowns have names like dropDown[0] and dropDown[1]. Instead, use the attribute contains selector (*=) to match any select element whose name includes the string "dropDown":
const dropDowns = document.querySelectorAll('select[name*="dropDown"]');
Next, collect the selected text from each dropdown
querySelectorAll returns a NodeList (a collection of elements), not a single dropdown. You can't just access options directly on the whole collection—you need to loop through each dropdown to grab its selected text. We'll convert the NodeList to an array and use map to gather all the values:
// Turn the NodeList into an array, then extract selected text from each dropdown const selectedTexts = Array.from(dropDowns).map(dropdown => { // Either of these lines will get the selected option's text return dropdown.options[dropdown.selectedIndex].text; // Alternative: return dropdown.selectedOptions[0].text; });
Finally, format and display the result
Now you can use join(', ') on the selectedTexts array to create a comma-separated string, then insert it into whatever element on your page you want to show the result (replace #displayResult with your actual target element's selector):
// Combine the texts into one string const displayText = selectedTexts.join(', '); // Show it on the page document.getElementById('displayResult').textContent = displayText;
Full working code (with error handling)
Here's everything put together, including a check for if no dropdowns are found:
const dropDowns = document.querySelectorAll('select[name*="dropDown"]'); // Exit early if there are no matching dropdowns if (dropDowns.length === 0) { console.log("No dropdowns with 'dropDown' in their name found"); return; } // Collect all selected option texts const selectedTexts = Array.from(dropDowns).map(dropdown => dropdown.options[dropdown.selectedIndex].text ); // Format and display the result const displayText = selectedTexts.join(', '); // Replace this with your target element's ID or selector document.getElementById('displayResult').textContent = displayText;
Don't forget to add a display element to your HTML
Make sure you have an element on the page where the result will appear, like this:
<div id="displayResult" style="margin-top: 20px;">Selected options will show here</div>
内容的提问来源于stack exchange,提问作者user2953989

