• Register now to get access to thousands of Tutorials, Leaked content, Hot NSFW and much more. Join us as we build and grow the community.

Advertise Here

Advertise Here

Advertise Here

Creating a Tags Input Field using CSS and JavaScript Tutorial

Invernes

Process Workflow Enhancer
I Rep
0
0
0
Rep
0
I Vouches
0
0
0
Vouches
0
Posts
130
Likes
101
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 2 1000 XP
In this tutorial, you can learn how to create a simple Tags Input Field for your web forms or CMS projects. The tutorial aims to provide students and beginners with a reference for learning of building a useful website or web application component and providing them with a free web library for generating Tag Input Fields. Here, I created a simple web page script using the simple library that I created to demonstrate the main goal of this article.

What is a Tags Input Field?

The Tag Input Field is a custom component of a website or web application form that allows the users to dynamically add, update, and remove multiple keywords. This component is often used in a Content Management System or CMS project which allows the author or writers to insert the meta keywords regarding the article they are about to publish. Basically, this feature is compressing the keywords into one field to save some space on the page screen and to easily manage the list of keywords.

How to create a Tags Input Field?

The Tags Input Field can be easily achieved using HTML elements, CSS, and pure JavaScript. Using HTML input, div elements, and some CSS we can build and design a simple form input or more likely a textarea where the keywords will be input. JavaScript will be helpful for giving a creative UI/UX for managing the keywords inside the text field. Check out the sample web page scripts that I provided below to have a better idea of creating this component for an actual web project.

Sample Web Page

The scripts below result in a simple web page that contains a form field for keywords or meta descriptions. The keywords are displayed with a small container with a remove link or button beside each keyword to remove it. It contains also a validation feature for checking duplicates.

Page Interface

The below script is the HTML file script named index.html. It contains the page layout's elements and the Tags Input Field Container.

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    CSS/JS - Tags Input Field</

    title

    >
  8. <link

    rel

    =

    "preconnect"

    href

    =

    "https://fonts.googleapis.com"

    >
  9. <link

    rel

    =

    "preconnect"

    href

    =

    "https://fonts.gstatic.com"

    crossorigin>
  10. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200"

    /

    >
  11. <link

    rel

    =

    "stylesheet"

    href

    =

    "style.css"

    >
  12. <link

    rel

    =

    "stylesheet"

    href

    =

    "tagInput.css"

    >
  13. <script

    src

    =

    "tagInput.js"

    ></

    script

    >

  14. </

    head

    >
  15. <body

    >
  16. <div

    id

    =

    "wrapper"

    >
  17. <div

    class

    =

    "page-title"

    >

    Dynamic Tags Input Field using JavaScript</

    div

    >
  18. <hr

    style

    =

    "width:25px"

    >
  19. <div

    id

    =

    "content-wrapper"

    >
  20. <div

    >
  21. <label

    ><span

    class

    =

    "material-symbols-outlined"

    >

    sell</

    span

    >

    Meta Tags</

    label

    >
  22. <!-- Tag Input Field -->
  23. <div

    id

    =

    "tagSampleField"

    ></

    div

    >
  24. <!-- Tag Input Field -->
  25. </

    div

    >
  26. </

    div

    >
  27. </

    div

    >
  28. <script

    >
  29. /*
  30. * Initialize Tag Input to selected Element
  31. * options = (object)
  32. * - placeholder
  33. * - inputName
  34. * - containerClass
  35. * - values (Array)
  36. */
  37. let SampleTagField = new TagInput('tagSampleField',{
  38. placeholder:"Enter Keywords Here...",
  39. inputName:'sampleTagField1',
  40. containerClass:'MyAdditionalClassName',
  41. // values: ['test1', '123']
  42. })
  43. SampleTagField.init()

  44. </

    script

    >
  45. </

    body

    >
  46. </

    html

    >

Here's the stylesheet of the web page that contains the CSS styles of the layout design of the page interface. The file script is known as the style.css that is loaded on the index page file script.

  1. @import

    url

    (

    'https://fonts.googleapis.com/css2?family=Rubik&display=swap'

    )

    ;
  2. @import

    url

    (

    'https://fonts.googleapis.com/css2?family=Courgette&family=Secular+One&display=swap" rel="stylesheet'

    )

    ;
  3. :

    root

    {
  4. --secular-font

    :

    'Secular One'

    ,

    sans-serif

    ;
  5. --satisfy-font

    :

    'Satisfy'

    ,

    cursive

    ;
  6. }
  7. *

    {
  8. box-sizing

    :

    border-box

    ;
  9. }
  10. body *

    {
  11. font-family

    :

    'Rubik'

    ,

    sans-serif

    ;
  12. }
  13. /**
  14. Page Design
  15. */
  16. body,
  17. html{
  18. height

    :

    100%

    ;
  19. width

    :

    100%

    ;
  20. margin

    :

    0

    ;
  21. padding

    :

    0

    ;
  22. }
  23. body{
  24. background-color

    :

    #789395

    ;
  25. }
  26. /* Page Wrapper */
  27. #wrapper

    {
  28. width

    :

    100%

    ;
  29. height

    :

    100%

    ;
  30. display

    :

    flex;
  31. flex-direction

    :

    column;
  32. align-items

    :

    center

    ;
  33. justify-content

    :

    center

    ;
  34. }
  35. .page-title{
  36. font-size

    :

    35px

    ;
  37. font-family

    :

    var

    (

    --secular-font

    )

    ;
  38. letter-spacing

    :

    2px

    ;
  39. text-align

    :

    center

    ;
  40. color

    :

    #fff

    ;
  41. text-shadow

    :

    0px

    0px

    5px

    #7070709c

    ;
  42. }
  43. /* Content Wrapper */
  44. #content-wrapper

    {
  45. width

    :

    550px

    ;
  46. min-height

    :

    200px

    ;
  47. background

    :

    #fff

    ;
  48. border

    :

    1px

    solid

    #cfcfcf

    ;
  49. box-shadow

    :

    1px

    1px

    5px

    #282828c4

    ;
  50. padding

    :

    2em

    1.5em

    ;
  51. }
  52. @media

    (

    max-width

    :

    550px

    )

    {
  53. #content-wrapper

    {
  54. width

    :

    100%

    ;
  55. }
  56. }
  57. label {
  58. display

    :

    flex;
  59. align-items

    :

    center

    ;
  60. margin-bottom

    :

    .5em

    ;
  61. }

Tag Input Fields Stylesheet

The script below is the CSS code that contains the styles of the Tag Input Field elements. This file is known as tagInput.css which is also loaded on the index page file script.

  1. /* Tag Input Field */
  2. .tag-input-field

    {
  3. margin-bottom

    :

    .5em

    ;
  4. }

  5. /* Text Field/Area of the keywords */
  6. .tag-input-field

    .tag-input{
  7. width

    :

    100%

    ;
  8. min-height

    :

    50px

    ;
  9. max-height

    :

    100px

    ;
  10. overflow-x

    :

    hidden

    ;
  11. display

    :

    flex;
  12. flex-wrap

    :

    wrap;
  13. border

    :

    1px

    solid

    #b4b4b4

    ;
  14. padding

    :

    .5em

    .5em

    ;
  15. }
  16. /* Text Field */
  17. .tag-input-field

    .text-field{
  18. outline

    :

    none

    ;
  19. padding

    :

    .35em

    ;
  20. }
  21. .tag-input

    .tag-item

    span[

    contenteditable=

    "true"

    ]

    {
  22. outline

    :

    none

    ;
  23. }
  24. /* Text Field Placeholder*/
  25. .tag-input-field

    :

    not

    (

    :

    has(

    .tag-item)

    )

    .text-field

    :

    empty

    :

    before

    {
  26. content

    :

    var

    (

    --inputPlaceHolder

    )

    ;
  27. font-size

    :

    15px

    ;
  28. font-style

    :

    italic

    ;
  29. color

    :

    #dbdbdb

    ;
  30. }

  31. /* Keyword items */
  32. .tag-input-field

    .tag-item{
  33. padding

    :

    .35em

    ;
  34. display

    :

    flex;
  35. align-items

    :

    center

    ;
  36. font-size

    :

    .9rem

    ;
  37. background-color

    :

    #ededed

    ;
  38. color

    :

    #3c3c3c

    ;
  39. margin-right

    :

    .35em

    ;
  40. margin-bottom

    :

    .35em

    ;
  41. }
  42. /* Item Remove Element */
  43. .tag-input-field

    .tag-item

    .tag-item-remove{
  44. text-decoration

    :

    none

    ;
  45. display

    :

    flex;
  46. align-items

    :

    center

    ;
  47. justify-content

    :

    center

    ;
  48. padding-left

    :

    .35em

    ;
  49. color

    :

    #222222

    ;
  50. cursor

    :

    pointer

    ;
  51. }
  52. .tag-input-field

    .tag-item

    .tag-item-remove

    :

    before

    {
  53. content

    :

    "\00D7

    "

    ;
  54. }
  55. /*Keywords Hidden inputs*/
  56. .tag-input-field

    .tag-input-added{
  57. visibility

    :

    none

    ;
  58. display

    :

    none

    ;
  59. }

  60. /*Clear All Keywords Element*/
  61. .tag-input-field

    div:

    has(

    .clear-tag-input)

    {
  62. display

    :

    flex;
  63. flex-wrap

    :

    wrap;
  64. justify-content

    :

    end

    ;
  65. }
  66. .tag-input-field

    .clear-tag-input{
  67. text-decoration

    :

    none

    ;
  68. color

    :

    #504f4f

    ;
  69. font-size

    :

    .8rem

    ;
  70. }

Tag Input Fields JavaScript

Lastly, the below script is the JS file script that contains the code for initializing and making the Tags Field functional. The script is written using the JS OOP Approach or JS Class Object. The file is known as tagInput.js and it is loaded also at the index page.

  1. /**
  2. * Tag Input Field Class Object
  3. * Description: Creates an Input Field where user can dynamically, update, and remove element.
  4. * Purpose: This was built for educational purposes only but can be also used in an actual project.
  5. * Developer: Carlo Montero ([email protected])
  6. */

  7. /**
  8. * Syntax
  9. * let myDiv = new TagInput('ElementId', optionsObject);
  10. * myDiv.init();
  11. */

  12. /**
  13. * Option Objects
  14. * placeholder (optional)- the text to be shown when the field is empty or not filled yet.
  15. * inputName (optional)- name of the input array for submitting the keywords (default: ElementID)
  16. * containerClass (optional)- additional class name of the tag field element
  17. * values (optional)[array] - Default Keywords
  18. */
  19. class

    TagInput {
  20. TagField;
  21. // Creating the Tag Input Field container
  22. tagFieldHTML =

    document.createElement

    (

    'div'

    )

    ;
  23. // Creating the Tag Input Field Item container
  24. tagItem =

    document.createElement

    (

    'div'

    )

    ;
  25. ItemConfirmKeyCodes =

    [

    13

    ,

    44

    ]

    ;
  26. options;
  27. constructor(

    ElementID,

    options =

    {

    }

    )

    {
  28. // Element Selector where to place the tag input
  29. this

    .TagField

    =

    document.getElementById

    (

    ElementID)

  30. // Tag Field HTML's properties
  31. this

    .tagFieldHTML

    .classList

    .add

    (

    'tag-input-field'

    )
  32. this

    .tagFieldHTML

    .innerHTML

    =

    `
  33. <

    div>
  34. <

    a class

    =

    "clear-tag-input"

    href=

    "#"

    title=

    "Remove All Keywords"

    tabindex=

    "-1"

    >

    Clear</

    a>
  35. </

    div>
  36. <

    div class

    =

    "tag-input"

    >
  37. <

    div class

    =

    "text-field"

    contenteditable=

    "true"

    ></

    div>
  38. </

    div>
  39. <

    div><

    small><

    em>

    Press Enter or add Comma (

    ,

    )

    to confirm the keyword</

    em></

    small></

    div>
  40. <

    div class

    =

    "tag-input-added"

    >
  41. </

    div>

    `;
  42. // Tag Field Items properties
  43. this

    .tagItem

    .classList

    .add

    (

    'tag-item'

    )
  44. this

    .tagItem

    .innerHTML

    +=

    `<

    span contenteditable=

    "true"

    >

    Sample keyword</

    span><

    a href=

    "#"

    class

    =

    "tag-item-remove"

    tabindex=

    "-1"

    ></

    a>

    `

  45. //Class options
  46. this

    .options

    =

    options
  47. this

    .options

    .inputName

    =

    this

    .options

    .inputName

    ||

    ElementID
  48. this

    .options

    .placeholder

    =

    this

    .options

    .placeholder

    ||

    "Enter keywords here..."
  49. }
  50. /** Initialize Tag Field */
  51. init(

    )

    {
  52. // Insert Tag Field Elements inside the given parent Element
  53. this

    .TagField

    .innerHTML

    =

    this

    .tagFieldHTML

    .outerHTML

  54. //Adding the addional Class Name if given
  55. if

    (

    !!

    this

    .options

    .containerClass

    )

    {
  56. this

    .TagField

    .classList

    .add

    (

    this

    .options

    .containerClass

    )
  57. }

  58. //Setting the placeholder text's CSS Variable
  59. this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    .style

    =

    `--

    inputPlaceHolder:

    '${this.options.placeholder}'

    `

  60. // Trigger focus to text field
  61. this

    .TagField

    .querySelector

    (

    '.tag-input'

    )

    .addEventListener

    (

    'click'

    ,

    (

    e)

    =>

    {
  62. e.preventDefault

    (

    )
  63. if

    (

    e.target

    ==

    this

    .TagField

    .querySelector

    (

    '.tag-input'

    )

    )
  64. this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    .focus

    (

    )
  65. }

    )

  66. // Event Listener when keypress
  67. this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    .addEventListener

    (

    'keypress'

    ,

    e=>

    {
  68. var

    code =

    e.keyCode

    ||

    e.which

  69. if

    (

    this

    .ItemConfirmKeyCodes

    .includes

    (

    code)

    )

    {
  70. e.preventDefault

    (

    )
  71. var

    textValue =

    this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    .innerText
  72. this

    .InsertKeyword

    (

    textValue)
  73. }
  74. }

    )
  75. //Clear/Remove All Keywords
  76. this

    .TagField

    .querySelector

    (

    '.clear-tag-input'

    )

    .addEventListener

    (

    'click'

    ,

    e =>

    {
  77. e.preventDefault

    (

    )
  78. this

    .removeAllKeywords

    (

    )
  79. }

    )

  80. /** Insert Default Values */
  81. if

    (

    !!

    this

    .options

    .values

    )

    {
  82. if

    (

    !

    Array

    .isArray

    (

    this

    .options

    .values

    )

    )

    {
  83. throw

    Error(

    'Tag Element Default Value requires an Array Value'

    )

    ;
  84. }

    else

    {
  85. this

    .options

    .values

    .forEach

    (

    textValue =>

    {
  86. this

    .InsertKeyword

    (

    textValue)
  87. }

    )
  88. }
  89. }
  90. }
  91. /** Insert Keyword as an Item */
  92. InsertKeyword(

    TextValue=

    ""

    )

    {
  93. var

    item =

    this

    .tagItem

    .cloneNode

    (

    true

    )
  94. var

    textValue =

    String

    (

    TextValue)

    .trim

    (

    )
  95. if

    (

    textValue ===

    ""

    )

    {
  96. return

    false

    ;
  97. }
  98. // List Current keyword iputs
  99. var

    currentInputs =

    [

    ...this

    .TagField

    .querySelectorAll

    (

    '.tag-input-added input'

    )

    ]
  100. // Check if Text Value already Exists
  101. var

    has_duplicate =

    currentInputs.filter

    (

    input =>

    (

    (

    input.value

    )

    .trim

    (

    )

    )

    .toLowerCase

    (

    )

    ==

    textValue.toLowerCase

    (

    )

    )
  102. if

    (

    has_duplicate.length

    <=

    0

    )

    {
  103. /** Insert If Not Existing Yet */
  104. var

    id =

    Math

    .floor

    (

    Math

    .random

    (

    )

    *

    (

    1000

    -

    1

    )

    +

    1

    )
  105. while(

    true

    )

    {
  106. if

    (

    this

    .TagField

    .querySelector

    (

    `.tag

    -

    item[

    data-

    id=

    '${id}'

    ]

    `)

    !==

    null

    )

    {
  107. id =

    Math

    .floor

    (

    Math

    .random

    (

    )

    *

    (

    1000

    -

    1

    )

    +

    1

    )
  108. }

    else

    {
  109. break

    ;
  110. }
  111. }
  112. item.dataset

    .id

    =

    id
  113. var

    input =

    document.createElement

    (

    'input'

    )
  114. input.dataset

    .id

    =

    id;
  115. input.name

    =

    `${

    this

    .options

    .inputName

    }

    [

    ]

    `;
  116. input.value

    =

    textValue
  117. item.querySelector

    (

    'span[contenteditable="true"]'

    )

    .innerText

    =

    textValue
  118. //insert Keyword input
  119. this

    .TagField

    .querySelector

    (

    '.tag-input-added'

    )

    .appendChild

    (

    input)
  120. //Insert Keyword Item
  121. if

    (

    this

    .TagField

    .querySelectorAll

    (

    '.tag-item'

    )

    .length

    >

    0

    )

    {
  122. this

    .TagField

    .querySelectorAll

    (

    '.tag-item'

    )

    [

    this

    .TagField

    .querySelectorAll

    (

    '.tag-item'

    )

    .length

    -

    1

    ]

    .after

    (

    item)
  123. }

    else

    {
  124. this

    .TagField

    .querySelector

    (

    '.tag-input'

    )

    .insertBefore

    (

    item,

    this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    )
  125. }
  126. //result text field
  127. this

    .TagField

    .querySelector

    (

    '.text-field'

    )

    .innerText

    =

    ''

  128. //Add event listner to item for updating the value
  129. item.querySelector

    (

    'span[contenteditable="true"]'

    )

    .addEventListener

    (

    'input'

    ,

    (

    e)

    =>

    {
  130. this

    .updateTagElement

    (

    item.querySelector

    (

    'span[contenteditable="true"]'

    )

    )
  131. }

    )
  132. item.querySelector

    (

    '.tag-item-remove'

    )

    .addEventListener

    (

    'click'

    ,

    (

    e)

    =>

    {
  133. e.preventDefault

    (

    )
  134. this

    .TagInputItemRemove

    (

    item)
  135. }

    )
  136. }

    else

    {
  137. //show dialog if keyword is already listed
  138. alert(

    "Keyword Already Exists!"

    )
  139. }
  140. }
  141. TagInputItemRemove(

    el)

    {
  142. // Function for removing the Item
  143. var

    item_id =

    el.dataset

    .id
  144. if

    (

    item_id !==

    undefined

    )

    {
  145. if

    (

    this

    .TagField

    .querySelector

    (

    `.tag

    -

    input-

    added [

    data-

    id=

    "${item_id}"

    ]

    `)

    !==

    null

    )

    {
  146. this

    .TagField

    .querySelector

    (

    `.tag

    -

    input-

    added [

    data-

    id=

    "${item_id}"

    ]

    `)

    .remove

    (

    )
  147. }
  148. }
  149. el.remove

    (

    )

    ;
  150. this

    .TagField

    .querySelector

    (

    '.tag-input'

    )

    .click

    (

    )
  151. }

  152. updateTagElement(

    el)

    {
  153. //Function for updating the Keyword input
  154. var

    item_id =

    el.parentElement

    .dataset

    .id
  155. var

    textValue =

    (

    el.innerText

    )

    .trim

    (

    )
  156. if

    (

    textValue !==

    ""

    )

    {
  157. if

    (

    item_id !==

    undefined

    )

    {
  158. if

    (

    this

    .TagField

    .querySelector

    (

    `.tag

    -

    input-

    added [

    data-

    id=

    "${item_id}"

    ]

    `)

    !==

    null

    )

    {
  159. this

    .TagField

    .querySelector

    (

    `.tag

    -

    input-

    added [

    data-

    id=

    "${item_id}"

    ]

    `)

    .value

    =

    textValue
  160. }
  161. }
  162. }

    else

    {
  163. this

    .TagInputItemRemove

    (

    el.parentElement

    )
  164. }
  165. }
  166. removeAllKeywords(

    )

    {
  167. //Clear/Remove Items function
  168. this

    .TagField

    .querySelectorAll

    (

    '.tag-item'

    )

    .forEach

    (

    item =>

    {
  169. item.remove

    (

    )
  170. }

    )
  171. this

    .TagField

    .querySelector

    (

    '.tag-input-added'

    )

    .innerHTML

    =

    ''
  172. this

    .TagField

    .click

    (

    )
  173. }
  174. }

Result

The following images are the snapshots of the results using the scripts I have provided above.

Page Layout

Tags Input Field

I have also provided the complete source code's zip file on this website and it is free to download. The download button is located below this tutorial's content.

In addition, the CSS and JS script is ready to use in an actual project or for your current and future projects. To implement it, follow the instruction below.

Steps for using the Tags Input Field Library

  1. Copy and paste the tagInput.css and tagInput.js into your project directory.
  2. Load the files inside your web page file scripts.

    Example
    1. <link

      rel

      =

      "stylesheet"

      href

      =

      "./tagInput.css"

      >
    2. <script

      src

      =

      "./tagInput.js"

      ></

      script

      >

  3. Add a new HTML div tag in your form page script with an id

    attribute. This element will serve as the parent container of the Tag Input Field.

    Example
    1. <div

      id

      =

      "tagField"

      ></

      div

      >

  4. Lastly, initiate the Tag Input Field like the following syntax:
    1. /*
    2. * Initialize Tag Input to selected Element
    3. * options = (object)
    4. * - placeholder (string) [optional]
    5. * - inputName (string) [optional]
    6. * - containerClass (string) [optional]
    7. * - values (Array) [optional]
    8. */
    9. let tagField =

      new

      TagInput(

      'tagField'

      ,

      {
    10. placeholder:

      "Enter Keywords Here..."

      ,
    11. inputName:

      'tags'

      ,
    12. containerClass:

      'MyAdditionalClassName'

      ,
    13. values:

      [

      'Sample Keyword 1'

      ,

      'Sample Keyword 2'

      ]
    14. }

      )
    15. tagField.init

      (

      )


There you go! I hope this Creating a Tags Input Field using CSS and JavaScript Tutorial and the free library will help you with what you are looking for and will be useful for your current and future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)


Download
You must upgrade your account or reply in the thread to view the hidden content.
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

452,503

355,786

355,795

Top