从多个动态文本框获取唯一值及单文本框值获取异常问题咨询
Hey there! Let's tackle your two problems one by one—first fixing the "only getting the last textbox value" bug, then implementing the unique value collection feature.
1. Fix: Getting the Correct Value for Each Textbox
The most common reason you're only seeing the last textbox's value is variable scoping issues when binding event listeners in a loop. For example, if you used var (which has function-level scope) instead of let (block-level scope), all event callbacks end up referencing the same variable, which holds the final index after the loop finishes.
Bad Code (Causes the Issue)
const textBoxes = document.querySelectorAll('.dynamic-input'); for (var i = 0; i < textBoxes.length; i++) { textBoxes[i].addEventListener('input', function() { console.log(textBoxes[i].value); // i is always the last index here! }); }
Fixed Solutions
Option 1: Use forEach (Cleanest Approach)
forEach creates a separate scope for each iteration, so you can safely reference the current textbox:
const textBoxes = document.querySelectorAll('.dynamic-input'); textBoxes.forEach(textBox => { textBox.addEventListener('input', function() { const currentValue = this.value; // Or use e.target.value console.log("Current textbox value:", currentValue); }); });
Option 2: Use let in a For Loop
let has block-level scope, so each loop iteration gets its own copy of the variable:
const textBoxes = document.querySelectorAll('.dynamic-input'); for (let i = 0; i < textBoxes.length; i++) { textBoxes[i].addEventListener('input', function() { console.log("Current textbox value:", textBoxes[i].value); }); }
Option 3: Event Delegation (For Dynamically Added Textboxes)
If you're adding textboxes after the page loads (e.g., via a "Add Textbox" button), bind the event to a parent container instead of individual elements:
// Assume all textboxes are inside #textbox-container document.getElementById('textbox-container').addEventListener('input', function(e) { if (e.target.classList.contains('dynamic-input')) { const currentValue = e.target.value; console.log("Current textbox value:", currentValue); } });
2. Implement: Get Unique Values from All Textboxes
To collect unique values, we'll gather all non-empty values, then use a Set (which automatically removes duplicates) to get the unique list.
Function to Get Unique Values
function getUniqueTextboxValues() { const textBoxes = document.querySelectorAll('.dynamic-input'); // Collect all non-empty, trimmed values const allValues = Array.from(textBoxes) .map(textBox => textBox.value.trim()) .filter(value => value !== ''); // Skip empty strings // Convert to Set to remove duplicates, then back to array const uniqueValues = [...new Set(allValues)]; return uniqueValues; } // Example usage const uniqueVals = getUniqueTextboxValues(); console.log("Unique values:", uniqueVals);
Optional: Update Unique Values in Real-Time
If you want to keep the unique list updated as users type, call the function inside the input event listener:
// Using event delegation for dynamic textboxes document.getElementById('textbox-container').addEventListener('input', function(e) { if (e.target.classList.contains('dynamic-input')) { const uniqueVals = getUniqueTextboxValues(); console.log("Updated unique values:", uniqueVals); // You can also display these values in the UI here } });
内容的提问来源于stack exchange,提问作者Mahesh

