I am trying to allow a user to input multiple tags and be able to remove them from the array by use of a text box, an example would be how stackoverflow lets you add tags when asking a question, i have been able to add the values to the array, however i get an error when i run the remove function. this is the javascript i have written below:
<script type="module">
import {getDatabase, ref, set, child, get} from "https://www.gstatic.com/firebasejs/9.6.6/firebase-database.js";
const db = getDatabase();
const ul = document.querySelector(".statementbox");
const input = ul.querySelector('.inputstate');
let tags = [];
function createTag(){
//removing li tas before adding so there will be no duplication
ul.querySelectorAll("li").forEach(li => li.remove());
tags.slice().reverse().forEach(tag =>{
let liTag = `<li>${tag} <i class="fas fa-times" onclick="remove(this,'${tag}')"></i> </li>`;
ul.insertAdjacentHTML("afterbegin", liTag); //adding li inside ul tag
});
}
function remove(element, tag){
let index = tags.indexOf(tag); // getting removing tag index
tags = [...tags.slice(0, index), ...tags.slice(index + 1)]; // removing the tag from the array
console.log(tags);
}
function addTag(e){
if (e.key === "Enter") {
let tag = e.target.value.replace(/\s+/g, ' '); //removing unwanted spaces from tag
if (tag.length > 1 && !tags.includes(tag)) { //if tag length is greater than one and does not already exist
tag.split(',').forEach(tag => {//splitting each tag from comma
tags.push(tag); //adding tag to the array
createTag();
});
}
e.target.value = "";
}
}
input.addEventListener("keyup", addTag);
</script>
I don't understand the cause of the error because i have done the research and the function is not inside another function nor is it linked to a script with src nor is it wrapped within another function, i tried adding the remove()
in a separate script and it did log it in the console, however when i do this my array comes up blank.
Please advise on what to do, thanks in advance.