0

I am trying to get a list of numbers from an input field in a very simple number pair counting program. I cannot get any value from my input field - no matter what input I give it console logs "". I'm sure it's an easy tweak I'm missing. The problem line is in handleSearch(): const searchList = input.value; countPairs is a function taking an int and an array and returning an int

document.getElementById("app").innerHTML = `
<h1 style="color:indigo">Let's Count Pairs of Socks!</h1>
<h3 style="color:indigo">Enter a list of number socks:</h3>
<div id=Lisa></div>
`;
const input = document.createElement("input");
input.setAttribute("placeholder", "22, 22, 33");
const Lisa = document.getElementById("Lisa");
Lisa.appendChild(input);
const button = document.createElement("button");
button.innerText = "Get number of pairs!";
button.style.color = "indigo";
Lisa.innerHTML += `<br><br>`;
Lisa.appendChild(button);
const results = document.createElement("div");
Lisa.appendChild(results);
const handleSearch = () => {
  const searchList = input.value;
  console.log(input.value);
  const numPairs = countPairs(searchList.length, searchList);
  const title = document.createElement("h3");
  title.innerText = "The number of pairs is.....";
  title.style.color = "indigo";
  const pairs = document.createElement("h4");
  pairs.innerText = numPairs;
  pairs.style.color = "indigo";
  Lisa.innerHTML += `<br><br>`;
  Lisa.appendChild(title);
  Lisa.appendChild(pairs);
};
button.addEventListener("click", handleSearch);
````````````````````````````````````````````````````````````

1 Answers1

0

When you do

someElement.innerHTML +=

This is equivalent to

someElement.innerHTML = someElement.innerHTML + ...

In other words, all the children get re-parsed according to the new HTML that was set.

If you previously created an element with createElement and put it as a child, if you do .innerHTML += on the parent, the created element will no longer be connected to the DOM - instead, a new element with the same HTML markup will be there instead. So, your input.value will be showing you the value of the input that's no longer there.

Change both occurrences of

Lisa.innerHTML += `<br><br>`;

to

Lisa.insertAdjacentHTML('beforeend', `<br><br>`);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks a bunch CertainPerformance for explaining that! Works perfectly now and I understand what happened ;) – Lisa Modenbach Sep 12 '21 at 19:15
  • When an answer solves your problem, you can consider marking it as Accepted (check the checkbox next to the answer) to indicate that the issue is resolved :) – CertainPerformance Sep 12 '21 at 20:00