Access tokenfield elements

0

I am creating tags of products through an Ajax search, similar to stackoverflow

$('#_keytags').tokenfield({
        autocomplete: {
        source: function(request,response){
            $.ajax({
                url: routes(4,2),
                type: "post",
                dataType: "json",
                data:{keys: request.term},
                success: function(data){
                    response(data);
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) { 
                    console.log(errorThrown);
                } 
            });
        },
        minLength: 1,
        select: function(event,ui){

        },
        delay: 100
      },
      showAutocompleteOnFocus: true
    });
  

My question is how can I add a id to these tags and how   go through these elements getting your id ?

    
asked by DoubleM 19.06.2018 в 09:54
source

2 answers

1

In the ajax where you receive the data after painting them you can use that same data to browse and find the labels that have the same name as the data.name for example:

success: function(data){
     response(data);
     $.each(data,function(i,item){
        $('#_keytags label:contains("'+item.nombre+'")').attr('data-id',item.id);
     });
},

What it does is find the labels that contain the text as well as the data that you receive and if it finds it, it assigns it the corresponding data-id as an attribute. As long as the text is contained in a label, if it is in a span you change label to span, and so with your specific case.

And finally with a:

var array = array();
$("#_keytags label").each(function(i,item){
    array.push($(item).attr('data-id'));
});

You go through all the data-ids of the labels and save them in an array

    
answered by 19.06.2018 / 11:32
source
0

According to the library documentation that you are using (link) , you have the possibility to define a " value "and a" label ", where the value would be your" id ":

$('#myField').tokenfield('setTokens', [
  { value: "blue", label: "Blau" }, 
  { value: "red", label: "Rot" }
]);
    
answered by 19.06.2018 в 10:32