I found a YouTube tutorial that showed me how to create a multiple tag input field but I couldn’t figure out how to save the inputs (as JSON) to my Django models.
I am new to JavaScript, so I don’t know what to do here.
My goal is to submit the tag inputs along with other inputs in my HTML form
JavaScript
const ul = document.querySelector("ul[name=features-ul]"),
input = document.querySelector("input[name=features]"),
tagNumb = document.querySelector(".tag-details span");
let maxTags = 16,
tags = ["coding"];
var features = {"input[name=features]" : tags}
countTags();
createTag();
function countTags(){
input.focus();
tagNumb.innerText = maxTags - tags.length;
}
function createTag(){
ul.querySelectorAll("li").forEach(li => li.remove());
tags.slice().reverse().forEach(tag =>{
let liTag = `<li>${tag} <i class="uit uit-multiply" onclick="remove(this, '${tag}')"></i></li>`;
ul.insertAdjacentHTML("afterbegin", liTag);
});
countTags();
}
function remove(element, tag){
let index = tags.indexOf(tag);
tags = [...tags.slice(0, index), ...tags.slice(index + 1)];
element.parentElement.remove();
countTags();
}
function addTag(e){
if(e.key == "Enter"){
let tag = e.target.value.replace(/s+/g, ' ');
if(tag.length > 1 && !tags.includes(tag)){
if(tags.length < 16){
tag.split(',').forEach(tag => {
tags.push(tag);
createTag();
});
}
}
e.target.value = "";
}
}
input.addEventListener("keyup", addTag);
const removeBtn = document.querySelector(".tag-details button");
removeBtn.addEventListener("click", () =>{
tags.length = 0;
ul.querySelectorAll("li").forEach(li => li.remove());
countTags();
});
$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
html
Property Features:
<div class="tag-wrapper">
<div class="tag-content">
<p>Press enter or add a comma after each tag</p>
<ul name="features-ul"><input type="text" id="features" spellcheck="false" name="features">
</ul>
</div>
<div class="tag-details">
<p><span>16</span> tags are remaining</p>
<button>Clear All Tags</button>
</div>
</div>
</div>
2
Answers
You need to add a button for submitting the tags to your HTML.
e.g.
Then you need add a function for submitting the tags and an event listener for the button.
e.g.
First of all you need to handle key 13 properly. Check out the relevant code. Also, my bad, the
tags
variable already contains the required JSON. So this should work to get the JSON. Also the answer of@Ervin van hoof
correctly sends it as AJAX to the server.