Maximizing the potential of JavaScript by utilizing effective tags

Looking to enhance my JavaScript code by adding a maximum tags option limited to 6 with no duplicates. Check out the current snippet below:

             <div id="tags">
                <span>php</span>
                <span>c++</span>
                <span>jquery</span>
                <input type="text" value="" placeholder="Add a tag" />
              </div>
<script>
$(function(){ // DOM ready    
  // ::: TAGS BOX    
  $("#tags input").on({
    focusout : function() {
      var txt= this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
      if(txt) $("<span/>",{text:txt.toLowerCase(), insertBefore:this});
      this.value="";
    },
    keyup : function(ev) {
      // if: comma|enter|space (delimit more keyCodes with | pipe)
      if(/(188|13|32)/.test(ev.which)) $(this).focusout();
    }
  });
  $('#tags').on('click', 'span', function() {
    if(confirm("Remove "+ $(this).text() +"?")) $(this).remove();
  });

});
</script>

Demo

Answer №1

I accomplished this task using the Select2 feature:

  • Utilizes tag style
  • Avoids repetitions
  • Allows a maximum of 3 selections

Code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Hello</title>
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
    <script>
      $(function () {
        $(".select2").select2({
          maximumSelectionLength: 3,
          width: 350
        });
      });
    </script>
  </head>
  <body>
    <select name="tags" id="tags" class="select2" multiple="multiple">
      <option value="PHP">PHP</option>
      <option value="CSS">CSS</option>
      <option value="CPP">C++</option>
      <option value="JavaScript">JavaScript</option>
    </select>
  </body>
</html>

Snippet

$(function () {
  $(".select2").select2({
    maximumSelectionLength: 3,
    width: 350
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
<select name="tags" id="tags" class="select2" multiple="multiple">
  <option value="PHP">PHP</option>
  <option value="CSS">CSS</option>
  <option value="CPP">C++</option>
  <option value="JavaScript">JavaScript</option>
</select>

Demo: JSBin

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to incorporate pagination with axios in my code

As a newcomer to the world of REACT, I am currently delving into the realm of implementing pagination in my React project using axios. The API that I am utilizing (swapi.dev) boasts a total of 87 characters. Upon submitting a GET request with , only 10 cha ...

Safari causing placeholders to be sliced

I'm having trouble creating attractive placeholders in Safari. This is how it currently appears. Codepen: https://codepen.io/anon/pen/RLWrrK https://i.sstatic.net/aChBs.png .form-control { height: 45px; padding: 15px; font-size: 16px; col ...

Error encountered in jQueryUI Autocomplete: the function 'this.source' is not defined

I have been working on incorporating a live search feature that scans through keys in a JSON obtained from a public API. To achieve this, I am utilizing Jquery UI. However, I encountered the following error and I am uncertain about how to resolve it. Un ...

What could be the reason behind jQuery replacing the entire span with .text?

I am dealing with the following HTML code snippet: <p><input id="revenue" type="text" value="100000" /><span id="howmuch"><a href="" class="ka_button small_button small_cherry" target="_self" style="opacity: 1; "><span>How Mu ...

IFrame transparency setting not recognized

I am encountering an issue with transparency when adding an iframe to a webpage. I have set the allowTransparency attribute of the iFrame to true, but upon inspecting the element using Internet Explorer's F12 Developer Tools, I noticed that although t ...

Transform JSON data into an HTML layout

I'm looking to design a structure that showcases JSON information using HTML div elements. For example, utilizing the h4 tag for headers, p tag for text descriptions, and img tag for images. Can anyone provide guidance on the most efficient approach ...

Steps for accessing a particular tab on a separate webpage

I am working on a home page that includes an IFrame displaying a separate HTML page. Within the embedded page, there is a link that, when clicked, should open another page in the same IFrame with a specified tab displayed. This new page contains 3 tabs, ...

Tips for implementing a repeater item to function beyond the ng-repeat directive

Recently, I decided to play around with AngularJS and now I seem to be facing a small issue with ng-class. Specifically, I'm attempting to change the color of an awesome font icon. <div ng-controller="MyCtrl"> <i ng-class="{'test': ...

The <span> element stubbornly resists aligning inline within a flexbox container

Within a flexbox a element, I have a div that contains a span with the class .time-pretext: <a class="option-container option-edit-time" href="#"> <div class="option-icon"><canvas id="time-canvas" width="128" height="128"></canvas&g ...

React developers are struggling with parsing XML data with ReactDOM

While working on my React application, I encountered an issue with parsing an XML file. When I hard code the XML data in my file listener, I get the correct answer (2): const raw = `<?xml version="1.0" encoding="ISO-8859-1" ?> <?xml-stylesheet ...

Ways to inform a subelement that a task is complete?

I have a child component that displays a list of orders passed from the parent. I want to include a "Reload" button inside the child component that, when clicked, triggers a function in the parent component to reload the orders. Upon clicking the reload b ...

Is it possible to execute a function once an element has finished loading?

I am facing a challenge with running the List_Sandbox functions after a specific each loop. This loop selects checkboxes that trigger a change event, rendering additional checkboxes that need to be selected. The issue arises when the List_Sandbox functio ...

The JQuery File-Upload plugin remains inactive even after a file has been chosen

I am currently working on integrating the JQuery File-Upload plugin (). The issue I'm facing is that it doesn't respond when a file is selected. Here are some potential problems to consider: No errors appear in the Chrome console. Selecting a ...

What techniques can be applied to utilize JSON data in order to dynamically create menu components using the map method?

My current challenge involves dynamically generating a set of menu items using data retrieved from a JSON file. I've attempted to achieve this by mapping the values with props, but it seems like I'm overlooking something. Below is the code snipp ...

Focus on the image displayed through instafeed.js

Using the Instafeed.js plugin to create a dynamic Instagram feed. Everything is working smoothly, but I'm struggling to center the images being retrieved by Instafeed. Despite trying various methods, I can't seem to get it to display as desired. ...

What to do when IE6/IE7 margins disappear after moving a relatively positioned floated div using jQuery's .hover()?

Sharing my code with you: http://jsbin.com/uhera3/edit Encountered an issue where the relatively positioned floated divs move to the left in IE7 when using jQuery's .hover() function. Any insights on how to resolve this problem? ...

Execute consecutive Angular2 functions in a sequential manner, one following the next

In my Angular2 project, I have a service that fetches data for dropdown menus on a form. However, when I call this service multiple times with different parameters in the form component initialization, only the last call seems to work, overriding the previ ...

Center the navigation links within the navigation block

I am using the startbootstrap-small-business template and customizing it to fit my requirements. I have inserted a new logo which caused me to adjust the height of the navbar to approximately 120px. Now, my goal is to vertically align the links on the righ ...

Get rid of all numbers from a jQuery selection except for the first and last

I am dealing with an array let numberArray = ["500", "600", "700", "800", "900", "1000", "1100", "1200"] My objective is to remove all elements except for the first and last ones. The challenge arises when the array contains only one value, as I must ens ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...