MaterializeCSS Chips autocomplete functionality gets data from datalist but it also allows user to add their own typed data as chip. There must be option to stop the user data when its not from the autocomplete datalist
Using the latest version v0.98.2 138be0b
Check this codepen: https://codepen.io/anon/pen/PmvEEQ
$('#country-chips').on('chip.add', function(e, chip){
// you have the added chip here
$.each(CountryJSONData.countrylist, function(index, country) {
if(chip.tag==country.country_name)
{
chip.id = country.country_id;
}
});
var data1 = $('#country-chips').material_chip('data');
if(chip.id==undefined)
{
data1.splice(data1.length-1,1);
//console.log("need to remove");
}
$('#country-chips').material_chip({
data: data1,
autocompleteOptions: {
data: CountryData,
limit: 4,
minLength: 1
}
});
//console.log(data1);
});
Any other suggestions also welcome.
A (perhaps) more efficient way of doing this could be:
$('#chips').on('chip.add', function(e, chip){
// check if valid chip
if( validChipsValues.indexOf(chip.tag) !== -1) return;
let target = $(e.target);
let index = parseInt(target.material_chip('data').indexOf(chip)) + 1;
target.children(`.chip:nth-child(${index})`).remove()
});
I have made a pull request for this issue, it basically adds the option to only allow to select data from the autocomplete, and validates if this is the case before adding a chip when pressing enter. PR #5725
Since #5725 hasn't got merge since 2018, I have come up with a workaround for those having the same issue. The @dorphalsig's approach didn't work for me (maybe the current API is different than those days). This sample will prevent the user to tag against the autocomplete data.
$('.chips.chips-autocomplete').chips({
autocompleteOptions: {
data: external_data
},
onChipAdd: function(e, chip) {
var $this = this;
$this.chipsData.forEach(function(e, index) {
if(!(e.tag in external_data))
$this.deleteChip(index);
})
}
})
Most helpful comment
Since #5725 hasn't got merge since
2018, I have come up with a workaround for those having the same issue. The @dorphalsig's approach didn't work for me (maybe the current API is different than those days). This sample will prevent the user to tag against the autocomplete data.