lukesrw
lukesrw

Reputation: 2000

Materialize CSS, show images for autocompleted chips

Documentation for Materialize chips shows you can make chips with images:

<div class="chip">
    <img src="images/yuna.jpg" alt="Contact Person">
    Jane Doe
</div>

This works fine - and when we come to the autocomplete option, this also works:

$('.chips-autocomplete').material_chip({
    autocompleteOptions: {
        data: {
            'Apple': null,
            'Microsoft': null,
            'Google': 'images/juna.jpg'
        },
        limit: Infinity,
        minLength: 1
    }
});

As we have specified "images/juna.jpg" as the value for the "Google" property in the object, this image shows up alongside the autocomplete dropdown when we begin typing "Goo".

However, when this dropdown item is selected, it simply adds a chip that says "Google" with a close button, no image. Is it possible to have the images show up alongside the text in the chip after it is created?

Upvotes: 2

Views: 1063

Answers (1)

markphd
markphd

Reputation: 1454

In my case I used the chip.add event to display the image when chip is entered. Basically I had to duplicate the data passed to the autocompleteOptions and used the chip.tag as key to match the correct image.

$('.chips').on('chip.add', function(e, chip){

  var data = {
    'Kyle Robinson': 'dist/images/user-01.jpg',
    'Rebecca Smith': 'dist/images/user-02.jpg',
    'Aaron Lloyd': 'dist/images/user-03.jpg'
  } //same data passed to autocompleteOptions

  var key = chip.tag;
  $(this).children('.chip').append('<img src="' + data[key] + '">');

});

Live example: jsFiddle

Edit: There is no need to duplicate the data, you can get it using:

$('.chips-initial').material_chip('data');

Upvotes: 1

Related Questions