JavaScript Search Tags

Hello, I am trying to make a tag-based search (the one you often see on Wordpress blogs to search articles by keywords).

I have managed to make one with simple functions here: code

However. I’ve noticed one error: If two tags are the same, the search would still add this tag twice. I’m kinda stuck on solving this so if you have any ideas please help!

Thank you!

It doesn’t look like the code performs a check of the tags already included, which would be required to prevent adding the same tag multiple times. Essentially what you need is every time before a tag is added, check the current tag list to see if that tag already exists, and if so then don’t add and perhaps give an error message to the user. The main thing is that you need to check the new tag to add against the existing ones, something like this in the addTags() function would work:

if (tags.includes(input.value)) {
  console.log("Error: tag already added.");
  // Any extra error code to be rendered on the page rather than printed to the console can be put in here
  return 0;
}

This essentially just checks if the input is already in the tags list, and if it is returns from the function without appending. You can add any extra functionality you like in here (for example; rendering an error message on screen, making the check case insensitive, clearing the input box for duplicates also) but that would be the base structure.

Thanks Adam.
For those who are interested, here’s the code:

function addTags() {
        if (tags.includes(input.value)) {
           input.value = '';
           input.focus();
        } else {
            tags.push(input.value.trim());
            input.value = '';
            render();
        }
}
1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.