I am facing an issue where new tags are not being created when I pre-fill values in the tags input field on Bootstrap

When working on the Product Edit Page, I successfully displayed the old data that was selected previously. However, I am facing an issue with adding new tags. The new tags do not appear when I press enter or space after typing in the input field. It is possible to remove existing tags though. Can someone please assist me with this?

HTML

  <div class="col-md-6 tags">
        <div class="form-group">
          <label class="lbl" for="">Tags</label>
            <input class="form-control tt-input" type="text" name="tags" data-role="tagsinput" id="tags"  >
         </div>
   </div>

SCRIPT

  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js"
    crossorigin="anonymous"></script>

 


 <script>
  var elt = $('#tags');
    elt.tagsinput({
    tagClass: function(item) {
     switch (item.continent) {
        case 'Europe'   : return 'label label-primary';
        case 'America'  : return 'label label-danger label-important';
        case 'Australia': return 'label label-success';
        case 'Africa'   : return 'label label-default';
        case 'Asia'     : return 'label label-warning';
    }
  },
  itemValue: 'value',
  itemText: 'text',
});
elt.tagsinput('add', { "value": 1 , "text": "Amsterdam"   , "continent": "Europe"    });
elt.tagsinput('add', { "value": 4 , "text": "Washington"  , "continent": "America"   });
elt.tagsinput('add', { "value": 7 , "text": "Sydney"      , "continent": "Australia" });
elt.tagsinput('add', { "value": 10, "text": "Beijing"     , "continent": "Asia"      });
elt.tagsinput('add', { "value": 13, "text": "Cairo"       , "continent": "Africa"    });


</script>

Image

https://i.sstatic.net/QlSg9.png

Answer №1

Your initial input data is in Object form.

{ "value": 1 , "text": "Amsterdam"   , "continent": "Europe"    }

When you enter data into the input, it is treated as a String rather than an Object type. If you have the itemValue option in tagsinput, it will not accept String data. You can utilize the onchange event to capture the text you typed in and add the desired data using the add method.

I have provided an example code snippet for your reference.

const preData = [{
    value: 1,
    text: "Amsterdam",
    continent: "Europe"
  },
  {
    value: 4,
    text: "Washington",
    continent: "America"
  },
  {
    value: 7,
    text: "Sydney",
    continent: "Australia"
  },
  {
    value: 10,
    text: "Beijing",
    continent: "Asia"
  },
  {
    value: 13,
    text: "Cairo",
    continent: "Africa"
  }
];
let elt = $('#tags');
$(elt).tagsinput({
  tagClass: (item) => {
    switch (item.continent) {
      case 'Europe':
        return 'label label-primary';
      case 'America':
        return 'label label-danger label-important';
      case 'Australia':
        return 'label label-success';
      case 'Africa':
        return 'label label-default';
      case 'Asia':
        return 'label label-warning';
      default:
        return 'label label-danger';
    }
  },
  itemValue: "value",
  itemText: "text",
})
$(document).ready(() => {

  preData.map((val, index) => {
    $(elt).tagsinput('add', val);
  })

  var realInputForTags = $('#tags').tagsinput('input');
  $(realInputForTags).change((e) => {
    // you need to customize value, continent value according to your requirements
    let newItem = {
      value: Math.random(),
      text: e.target.value,
      continent: "xxx continent"
    }
    $(elt).tagsinput('add', newItem);
    e.target.value = "";
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.css" integrity="sha512-xmGTNt20S0t62wHLmQec2DauG9T+owP9e6VU8GigI0anN7OXLip9i7IwEhelasml2osdxX71XcYm6BQunTQeQg==" crossorigin="anonymous"
  referrerpolicy="no-referrer" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput-typeahead.css" integrity="sha512-wu4jn1tktzX0SHl5qNLDtx1uRPSj+pm9dDgqsrYUS16AqwzfdEmh1JR8IQL7h+phL/EAHpbBkISl5HXiZqxBlQ==" crossorigin="anonymous"
  referrerpolicy="no-referrer" />




<div class="col-md-6 tags">
  <div class="form-group" id="tagsInputDiv">
    <label class="lbl" for="">Tags</label>
    <input class="form-control tt-input" type="text" name="tags" data-role="tagsinput" id="tags" />
  </div>
</div>

This code serves as a demonstration of how it operates. Feel free to ask any questions by leaving a comment.

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

display data labels within the chart - utilizing the power of angular.js in conjunction with chart.js

My goal is to display the chart's information without requiring the user to hover over any part of the chart. I am utilizing Chart.js with Angular.js I have the same question as this one posted here: question here! html code: <div class="wrapper ...

Learn the process of invoking an Angular scope function from within a JavaScript function located within a controller

In my Angular controller, I have a JavaScript function where I am trying to call an Angular function. However, I am encountering the error: $scope.Name is not a function, $scope.dates is not a function. function validation() { $scope.page ...

Even after setting [attr.disabled]="false" in Angular, the Textarea still remains disabled

I am currently utilizing ngModel for a textarea, and I would like to be able to enable and disable the textarea based on a certain condition. Even though I have bound it correctly and the value is changing to [attr.disabled]="false", the textarea remains d ...

Execute a JavaScript function when an HTML list element is clicked

As a beginner in web development, I have a question that might seem obvious to some. I want to create a menu where each item, when clicked, triggers a JavaScript function with the item's ID as an argument. I plan to display the menu items in an unorde ...

Tips for simulating Axios requests in Jest

During my development process, I have implemented a function in my client/index.js file that utilizes axios to make HTTP requests import axios from "axios"; const createRequest = async (url, method) => { const response = await axios({ ...

Tips for creating a breakpoint in Sass specifically for a 414px iPhone screen size

For my latest project, I am utilizing sass and looking to incorporate a sass breakpoint or media query. My goal is to have the code execute only if the screen size is 414px or less. Below is my existing code: @include media-breakpoint-down(sm) { .sub-men ...

What could be causing these transformed canvases to not display fully in Chrome at specific resolutions?

fiddle: https://jsfiddle.net/f8hscrd0/66/ html: <body> <div id="canvas_div"> </div> </body> js: let colors = [ ['#000','#00F','#0F0'], ['#0FF','#F00','#F0F&a ...

Troubleshooting issues with cross-domain jQuery ajax requests

Struggling with this code and unable to make it work. This call consistently returns a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error message. $('#btnZendesk').click(function () { $.ajax({ ...

CSS3 rotation animation - begins to rotate and then halts at a specific angle

I attempted to develop a function that initiates a spin, replaces an image, and then stops the spin. However, when I remove the spin class, it jerks abruptly. How can I halt the spinning smoothly at a specific frame? setTimeout(function() { $('. ...

Troubleshooting Problem in Coursera's AngularJS Week 3 Exercise 4

Here's the issue I'm facing: After launching the index page with 'gulp watch', there's nothing visible on the screen. An error appears: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.12/$injector/modulerr?p ...

Applying styled numbering to elements using nth-child selector in

I have a div with multiple p tags inside. My goal is to assign them numbers using CSS. The number of p tags may vary. By using the :nth-child() selector and the ::before pseudo-element, I can achieve something like this: div p:first-child::before { ...

What exactly does "blocking and tackling" refer to in the Angular2 documentation?

As I delved into the online documentation for angular2, I stumbled upon a puzzling term - "blocking and tackling" in the ADVANCED - Angular Module chapter (https://angular.io/docs/ts/latest/guide/ngmodule.html). ... "It's all just basic blocking and t ...

Populate Jquery datatables programmatically

After implementing the Jquery Datatables plugin, I initially had hardcoded content in the table. However, I made some modifications to dynamically populate the table with fetched data. While this change worked fine, I encountered issues with the search f ...

Using Python to Detect a Late-Rendered Image on a Webpage Using JSON

I'm currently in the process of reviewing a list of URLs to verify the presence of a specific image. So far, I have experimented with both selenium and beautiful soup but haven't been able to crack it. The appearance of the image is represented ...

Tips on accessing dictionaries with multiple values in JavaScript

I am struggling with a particular dictionary in my code: {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']} My goal is to print the key and values from this dictionary. However, the code I att ...

Create a wait function that utilizes the promise method

I need to wait for the constructor() function, which contains an asynchronous method handled by Promise. My goal is to wait for two asynchronous methods within the constructor, and then wait for the constructor itself. However, my code is throwing an err ...

Using Google Maps to Cluster Markers on Your Website

I need to display numerous markers on a map for my website. My inquiry is whether the google maps api for javascript still supports clustering for websites? I attempted using marker cluster and it seems like it's not functioning properly. If so, can ...

What is the best way to retrieve the textbox value when its associated checkboxes have been selected?

Upon selecting a checkbox and entering data into the linked textbox, upon submission I aim to reveal a form showcasing both the entered text and which checkboxes were selected. ...

Visualizing connections between elements using SVG from JSON data files

As a newcomer to D3, I am facing challenges in visualizing my json file. My task involves plotting the locations (sites) as circles with their radius determined by the "amount" value. The concept of working with nodes and links is causing me great confusio ...

c# simulating button click through injected JavaScript

Greetings, I'm seeking assistance in replicating a specific button click on a website. Here is the code for the button: <button type="button" class="btn btn-link btn-xs" onclick="getComponents('188855', '5a0f44a9d70380.12406536&apo ...