LoginSignup
0
0

【HTML】削除ボタン付きタグのサンプル

Last updated at Posted at 2024-02-22

削除ボタン付きタグとは?

こういうの。

image.png

コード

ChatGPT3.5くんがほぼ作ってくれました。
マジで便利。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tagged Select List</title>
<style>
  .tag-list {
    display: flex;
    flex-wrap: wrap;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  .tag {
    display: flex;
    align-items: center;
    background-color: #f0f0f0;
    padding: 3px 6px;
    margin: 3px;
    border-radius: 3px;
  }
  .tag-name {
    margin-right: 5px;
  }
  .tag-close {
    cursor: pointer;
  }
</style>
</head>
<body>

<div class="tag-list" id="tagList">
  <!-- タグがここに追加されます -->
</div>

<select id="itemSelect" onchange="addItem()">
  <option value="item1">アイテム1</option>
  <option value="item2">アイテム2</option>
  <option value="item3">アイテム3</option>
  <option value="item4">アイテム4</option>
</select>

<script>
  function addItem() {
    const select = document.getElementById('itemSelect');
    const selectedItem = select.options[select.selectedIndex].text;

    const tagList = document.getElementById('tagList');

    const tag = document.createElement('div');
    tag.classList.add('tag');
    tag.innerHTML = `
      <span class="tag-name">${selectedItem}</span>
      <span class="tag-close" onclick="removeItem(this)">❎</span>
    `;

    tagList.appendChild(tag);
  }

  function removeItem(element) {
    element.parentNode.remove();
  }
</script>

</body>
</html>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0