我不知道如何提交多个标签输入

发布于 2025-02-10 23:17:04 字数 2893 浏览 1 评论 0原文

我找到了一个YouTube教程,向我展示了如何创建多个标签输入字段,但是我不知道如何将输入(作为JSON)保存到我的Django模型中。 我是JavaScript的新手,所以我不知道在这里该怎么办。

我的目标是提交标签输入以及我的HTML表单中的其他输入

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

属性功能:

                                        <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>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

随波逐流 2025-02-17 23:17:04

您需要添加一个按钮将标签提交到HTML。

例如

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

,您需要添加一个函数,以提交标签和一个按钮的事件侦听器。

例如

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();
});

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();
});
疯狂的代价 2025-02-17 23:17:04

首先,您需要正确处理密钥13。查看相关代码。另外,我的不好,标签变量已经包含所需的JSON。因此,这应该有效地获得JSON。另外,@ervin van Hoof的答案将其作为AJAX正确发送到服务器。

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>

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文