Bootstrap Tags Input, assign class to tags based on ajax call

风流意气都作罢 提交于 2019-12-11 05:38:31

问题


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');
    }
  }
});
});

来源:https://stackoverflow.com/questions/41025608/bootstrap-tags-input-assign-class-to-tags-based-on-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!