I got a question concerning JS localStorage()-function in connection with the querySelectorAll(). Here's my code:
const comments = Array.from(document.querySelectorAll('input[type="submit"]'));
comments.forEach(comment =>
{
comment.addEventListener('click', custom_text);
});
function custom_text() {
let inputs = Array.from(document.querySelectorAll('input[type="text"]'));
let textblocks = Array.from(document.querySelectorAll('div.comment_form'));
let length = inputs.length;
for (let i = 0; i < length; i++) {
if (inputs[i].value !== "") {
let text = document.createTextNode("User says: " + inputs[i].value);
let para = document.createElement("div");
localStorage.setItem("comment" + i, inputs[i].value);
let test = localStorage.getItem("comment" + i);
console.log(test);
para.appendChild(text);
textblocks[i].appendChild(para);
inputs[i].value = "";
}
}
}
And the HTML:
<div class="d-flex">
<input class="form-control ms-2 border-0" type="text" name="commenttext" placeholder="Kommentieren ..." size="50">
<input class="btn btn-link m-2 text-decoration-none" type="submit" name="comment" value="post">
</div>
<div class="ms-2">
<span href="#" class="text-decoration-none text-black-50 custom_font">All comments:</span>
<div class="fw-lighter comment_form">
</div>
</div>
Keep in mind that this is not the only comment-form, as there are a lot of posts with the exact html-tags on the site. I would like to save every comment with localStorage - my problem was, that I could just save one comment per comment-field, so if I would post another one, the last one was overwritten... Also I do not just want to console.log it, I want it to be child of "para", which also won't work.
I hope I made my question clear enough and I would be happy if someone could help me :)