Shalom Shalom - 11 months ago 108
jQuery Question

Initialize material design bootstrap tag

I'm using Material Design Tags in my Laravel application.

<div class="chips chips-placeholder chips-initial"></div>


I want to initialize this chips element with values stored in a database:

["kingfisher", "art"]


And in blade I'm getting
$art->keywords
as following:

array:1 [▼
0 => "art"
]


How can I assign this value to below jQuery code?

$('.chips-initial').material_chip({
data: [{
tag: 'Tag 1',
}, {
tag: 'Tag 2',
}, {
tag: 'Tag 3',
}],
});


I tried this:

var keywords[] = "{{ json_encode($art->keyword) }}";
console.log(keywords);
$.each(keywords, function( index, value ) {
alert( index + ": " + value );
})


But then i recieve the following error:


Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
["art"]


I also tried this:

var keywords = "{{ json_encode($art->keyword) }}";
$.each(JSON.parse(keywords), function( index, value ) {
alert( index + ": " + value );
});


Recieving this error:


Uncaught SyntaxError: Unexpected token & in JSON at position 1


Everything is ok if the array is numeric ie,
[1,2,3]

Answer Source
var keywords = '{{ json_encode($art->keyword) }}';
var data = JSON.parse(keywords.replace(/&quot;/g,'"'));
console.log(data);
var options = '';
$.each(data, function( index, value ) {
    options = options + "{tag: "+"'"+ value +"'"+",}";
    if(index < data.length){
        options = options + ","
    }
});

console.log(options);
$('.chips-initial').material_chip({
    data: [ ' + options + ' ],
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download