问题
I have a form where I'm putting the chipsData
into a hidden input field called #hiddenTags
I'm doing this because I don't want you use an AJAX call because I have a pre-exist form. Below is how I'm putting the chip data into the hidden input.
$("form").on("submit", function() {
var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags);
$('#hiddenTags').val( sendTags );
});
I'm sending it to the database like this: (PHP)
$this->tags = json_encode( $data['tags'] );
However, saving data like this is raising all sorts of issues. I'm using Twig to display the data.
Below is how I'm trying to display it, however with this I get an error unexpected token & in json
$('.chips').chips();
$('.chips-initial').chips({
data: {{ json }}
});
I have also tried putting the json into a hidden input and then putting it into jquery:
<input id="raw_json" type="hidden" hidden value="{{ user.tags }}">
var json = $('#raw_json').val();
$('.chips').chips();
$('.chips-initial').chips({
data: json
});
However, with this I get and error of Cannot read property 'length' of undefined
Apologies if I'm doing something stupid and/or completely wrong, any help is much appreciated.
回答1:
So the answer to your problems lies in setting the values when initializing the chips object, along with parsing the JSON data.
From there just keep the text box updated on add or delete of a chip.
var chipsData = JSON.parse($("#Tags").val());
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
data: chipsData,
onChipAdd: (event, chip) => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
},
onChipSelect: () => {
},
onChipDelete: () => {
var chipsData = M.Chips.getInstance($('.chips')).chipsData;
var chipsDataJson = JSON.stringify(chipsData);
$("#Tags").val(chipsDataJson);
}
});
来源:https://stackoverflow.com/questions/51342931/how-to-store-and-retrieve-materializecss-chips