skip to Main Content

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


  1. You need to add a button for submitting the tags to your HTML.

    e.g.

    <div class="tags-submit">
        <button>Submit tags</button>
    </div>
    

    Then you need add a function for submitting the tags and an event listener for the button.

    e.g.

    function submitTags() {
      fetch("http://url-here/to/send/tags", {
        method: "POST",
        headers: {'Content-Type': 'application/json'}, 
        body: JSON.stringify({tags: tags})
      }).then(res => {
        console.log("Request complete! response:", res);
      });
    }
    
    
    const submitBtn = document.querySelector(".tags-submit button");
    submitBtn.addEventListener("click", () =>{
        submitTags();
    });
    
    Login or Signup to reply.
  2. 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.

    const ul = document.querySelector("ul[name=features-ul]"),
      input = document.querySelector("input[name=features]"),
      tagNumb = document.querySelector(".tag-details span"),
      btn2 = document.querySelector(".btn2")
    
    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();
    });
    
    btn2.addEventListener("click", function() {
      console.log(tags)
    })
    
    $(document).ready(function() {
      $(input).keydown(function(event) {
        if (event.keyCode == 13) {
          event.preventDefault();
          return false;
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>
        <button class="btn2">
        show JSON
        </button>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search