将带有 jquery 的值插入到标记输入元素中

Insert value with jquery to tags input element

我想通过 jquery 将值插入标记输入元素 html。但是没用。

我的代码 JS :

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

我的代码 html :

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

但是结果是空的

我想要的结果是

我该怎么做?请帮我。谢谢

需要使用tagsinput的add方法

$(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" />

在初始化插件之前更改设置值的顺序,并且可以正常工作。

如果您初始化插件,您需要使用插件方法来插入标签值

$(document).ready(function() {
  var tagsValue = 'Jakarta,Bogor,Bandung';
  $('#tags-input').val(tagsValue).tagsinput();
});
.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" />