JavaScript Issue: Orphaned Suggestion Boxes on Field Removal

Clicking on X doesn't remove the dropdown menu

While working on my Boolean Search String Generator web app, I encountered a small but annoying UI bug. The app allows users to add and remove input fields dynamically, each offering live suggestions via a dropdown as the user types.

Originally, the addField function created input fields and a remove button like this:

function addField(sectionId) {
  const container = document.getElementById(sectionId);
  const div = document.createElement("div");
  div.className = "input-group";
  const input = document.createElement("input");
  input.type = "text";
  input.placeholder = `Enter value...`;
  input.oninput = () => filterSuggestions(input, sectionId); // Trigger suggestion on input change
  const removeBtn = document.createElement("button");
  removeBtn.textContent = "X";
  removeBtn.onclick = () => div.remove();
  div.appendChild(input);
  div.appendChild(removeBtn);
  container.appendChild(div);
}

🔍 The Problem

When an input field was removed using the “X” button, its suggestion dropdown (if visible) would remain orphaned in the DOM. This happened because the dropdown wasn’t part of the input field itself, and I was only removing the field wrapper (div), not any suggestion box that might have been attached to it.

✅ The Fix

I modified the remove logic to explicitly look for and remove any .suggestions element within the input’s wrapper div. Here’s the updated code:

function addField(sectionId) {
  const container = document.getElementById(sectionId);
  const div = document.createElement("div");
  div.className = "input-group";
  const input = document.createElement("input");
  input.type = "text";
  input.placeholder = `Enter value...`;
  input.oninput = () => filterSuggestions(input, sectionId); // Trigger suggestion on input change

  const removeBtn = document.createElement("button");
  removeBtn.textContent = "X";

  removeBtn.onclick = () => {
    const suggestionBox = div.querySelector(".suggestions");
    if (suggestionBox) {
      suggestionBox.remove();
    }
    div.remove();
  };

  div.appendChild(input);
  div.appendChild(removeBtn);
  container.appendChild(div);
}

🧩 Outcome

With this update, removing an input field also cleans up any attached suggestion dropdowns, leaving the DOM in a clean state and avoiding visual glitches.

Scroll to Top