Vladyslav Tyshchenko
Vladyslav Tyshchenko

Reputation: 53

How can I populate materialize.css chips autocomplete data?

There is an example with pre-written values:

$('.chips-autocomplete').material_chip({
    autocompleteData: {
      'Apple': null,
      'Microsoft': null,
      'Google': null
    }
  });

But I need to populate values dynamically from array which contains several string values. I tried something like this, but it doesn't work.

my_data = $.parseJSON(data);                        

$('.chips-autocomplete').material_chip({
    autocompleteData: {
        $.each(my_data, function(index, value) {
            value : null;                           
        });
    }                                                       
});

Upvotes: 5

Views: 5461

Answers (2)

lfontana
lfontana

Reputation: 31

I've been working around these chips with autocomplete. Here is a snippet that may help others in need.

MySql query result into JS Chip array format:

$database = new Database();
$db_link = $database->connect();

$sql = "SELECT Nombre, Descripcion FROM estudio_componente;";

$gsent = $db_link->prepare($sql);
$gsent->execute();

$result = $gsent->fetchAll(PDO::FETCH_ASSOC);

$return_arr = array();

foreach($result as $row) {
 $componentes[$row['Nombre']] = null    ;
}

echo json_encode($componentes);

Results:

{"Sangre":null,"Orina":null,"Glucemia":null}

enter image description here

Upvotes: 1

Albert Min
Albert Min

Reputation: 46

You can create your object first before passing it in:

<div class="chips chips-autocomplete"></div>

var my_data = {
  "0":"Apple",
  "1":"Microsoft",
  "2":"Google"
}

var myConvertedData = {};

$.each(my_data, function(index, value) {
  myConvertedData[value] = null;
});

$('.chips-autocomplete').material_chip({
  autocompleteData: myConvertedData
});

JSFiddle

Upvotes: 3

Related Questions