Search code examples
jquerybootstrap-tags-input

jQuery / Tags Input - Select element by its content


appreciate if you can help me with my problem. I have 20-30 elements like that one:

<div class="file file-unchosen">
  <div class="file-name-title">
    "File-title"
  </div>
</div>

where .file is used for css-styling of block

and I have bootstrap tags input list where I can store chosen files with function:

$('.file').click(function() {
  $(this).toggleClass('file-unchosen file-chosen');
  function addWork(elem) {
    var workname = $(elem).find('.file-name-title').text();
    $('#chosen-works-list').tagsinput('add', workname);
  };
  addWork(this);
});

The problem is, I cannot understand how to make .file unchosen againg when I remove it from tags input list. Now I'm in the middle of something like this (doesn't work anyway):

$('#chosen-works-list').on('itemRemoved', function(event) { //when tag is removed from tags list
  var chosenWorks = [];
  $('.file-chosen').each(function(i,elem) { //we take all of the chosen files
  console.log(elem); //log them
  chosenWorks.push($(elem).find('.file-name-title').text().toString());
                }); //push them to array
  var delWork = event.item; //define deleting tag
  ...and I don't know what to do next..
 });

Theoretically, next step must check if $(.file-chosen .file-name).text() equals $(delWork) and toggle its class, but cannot figure out how to do that.


Solution

  • Try this:

    <div class="file file-unchosen" data-content="deleted-tag-content">
    

    Then act on it like this:

    $('.file[data-content="'+ delWork +'"]').toggleClass('file-unchosen file-chosen');
    

    Dont hesitate to use data attributes, and query by them.