Search code examples
htmljquerybootstrap-tags-inputjquery-tags-input

Insert value with jquery to tags input element


I want to insert value through jquery to tags input element html. But didn't work.

My code JS :

$(document).ready(function(){        
  $('#tags-input').tagsInput();
  var tagsValue = 'Jakarta,Bogor,Bandung';
  $('#tags-input').val(tagsValue);
});

My code html :

<input type="text" class="form-control" name="city" id="tags-input" />   

But the result is empty wrong result

And i want the result is true result

how can i do it? Please help me. Thank you


Solution

  • You need to use the add method of tagsinput.

    $(document).ready(function(){        
      var tagInputEle = $('#tags-input');
      tagInputEle.tagsinput();
      tagInputEle.tagsinput('add', 'Jakarta');
      tagInputEle.tagsinput('add', 'Bogor');
      tagInputEle.tagsinput('add', 'Bandung');
    });
    .bootstrap-tagsinput .tag {
       background: red;
       padding: 4px;
       font-size: 14px;
    }
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" 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" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-tagsinput/0.8.0/bootstrap-tagsinput.min.js" integrity="sha512-9UR1ynHntZdqHnwXKTaOm1s6V9fExqejKvg5XMawEMToW4sSw+3jtLrYfZPijvnwnnE8Uol1O9BcAskoxgec+g==" crossorigin="anonymous"></script>
    
    <input type="text" class="form-control" name="city" id="tags-input" />