Bootstrap Tags Input, assign class to tags based o

2019-07-30 02:45发布

问题:

In Bootstrap Tags Input Plugin I can assign different colors to each tags through tagClass attribute. But I want to get this done by asynchronus ajax call.

In short I want default color, validation success color, and validation failure color.

When I make synchronus jQuery.ajax call, it works fine (as shown in code), but I can't do it with async set to true.

var elt = $('#multiple');
elt.tagsinput({
  maxTags: 7,
  trimValue: true,
  tagClass: function(item) {
    var val = $.ajax({
  url: 'http://localhost/reg/candidate/?id='.concat(item),
  dataType: 'json',
  async: false,
});

if (val.status==200){
  console.log(val)
  if((val.responseJSON).resp){
      return 'label label-success';
  }
}


return 'label label-danger';

  },
  confirmKeys: [13, 44,32, 188]
});

I don't want to use prefetch as there could be huge amount of data items on server.

Edit: I have found a hacky way to achieve the goal. But I would like to know any good option.

elt.on('itemAdded', function(event) {
$.ajax({
  url: 'http://localhost/reg/candidate/?id='.concat(event.item),
  dataType: 'json',
  //async: false,
  success: function(data){
      $("span.tag:contains("+event.item+")").removeClass("label-info",1000,"easeInBack");
    if(data.resp){
    $("span.tag:contains("+event.item+")").addClass('label-success');
    }
    else{
      $("span.tag:contains("+event.item+")").addClass('label-danger');
    }
  }
});
});