0

For some reason the keyText variable isn't showing any value when it should concat for each variable in keywords.

When someone clicks the button it runs addKeyword and grabs the value of the input.

Tried to Console.Log the keyText variable and didn't work at all.

var keywords = [];
      var keyText = "";

      function addKeyword() {
          var keywordName = document.getElementById("keywordAdd").value
          keywords.push(keywordName);

          keywords.forEach(showKeywords);

          function showKeywords(item, index) {
              var newString = "<span class='keyword' onclick='delKeyword(" + index + ")'>✖ " + item + "</span>";
              keyText.concat(newString);
              document.getElementById("keywords").innerHTML = keyText;
          }

      }

No Errors shown in Console. Expected result is a list of but doesn't show.

0

2 Answers 2

4

The problem is that .concat doesn't mutate the string, it returns a new string. You need to do something like this:

keyText = keyText.concat(newString);

By the way, your current approach is not that efficient because it changes the element's inner HTML at each iteration. You should probably do that only once after the HTML for all the elements is generated. Here is another approach that does that:

const result = keywords.map((item, index) => (`<span class="keyword" onclick="delKeyword(${index})">✖ ${item}</span>`)).join('');
document.getElementById("keywords").innerHTML = result;
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect solved it. However now whenever I click the button it relists current keywords saved to the array all over again rather than just adding a singular one.
@Policeboy109 You can reset (keyText = "") the variable that you're using, you can do that after the keywords.forEach(showKeywords); call.
0

Titus answer is correct, but you can simply use :

keyText += newString;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.