Fullcalendar dynamic data parameter and elaborate response - javascript

I'm using fullcalendar with events retrieved by ajax call. The URL has a dynamic parameter that is the room id because I would like to show the calendar based on room choice. I have two problems:
events is called before the user can choose the room (room selection and calendar is loaded at the same time), so the ajax URL is not valid because there isn't the room id. Is it possible to avoid the first loading?
The ajax response is in a particolar format like this:
{
"status":true,"success":true,"result":
[
{
"id":2,"title":"test","start":"2017-07-06T10:30:00","end":"2017-07-06T11:30:00"
},
{
"id":3,"title":"test","start":"2017-07-07T16:30:00","end":"2017-07-07T17:30:00"
}
],
"error":null
}
so I have to use only result field but eventDataTransform doesn't work with a JSON different from event format. Do you know if is it possible to elaborate the response before using it for the event?(I also use status and error to show message)
This is my actual code:
var calendar = $('#calendar').fullCalendar({
selectOverlap: false,
height: 600,
defaultView: 'agendaDay',
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaDay'
},
slotMinutes: 30,
minTime: '08:00:00',
maxTime: '18:00:00',
firstDay: 1,
editable: true,
weekends: false,
//this allow the click on month agenda and go to day agenda
dayClick: function(date, jsEvent, view) {
if(view.name == 'month') {
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', date);
}
},
eventDataTransform: function(eventData){
return eventData.result;
},
//load room reservation
events: {
url: '/booking/reservation/',
data: function () { // a function that returns an object
return {
idRoom: bookingForm.room,
};
}
}
});
bookingForm.room is loaded on select event:
roomTable.off('select')
.on( 'select', function ( e, dt, type, indexes ) {
bookingForm.room = roomTable.rows( indexes ).data().toArray()[0].idRoom;
$("#calendar").fullCalendar("refetchEvents");
} );

It is possibile to avoid the first loading?
Sure, simply don't set the events property and load the events later with addEventSource
See following example please:
var source =
[
{
title : 'event1',
start : '2017-07-01'
},
{
title : 'event2',
start : '2017-07-05',
end : '2017-07-07'
},
{
title : 'event3',
start : '2017-08-09T12:30:00',
allDay : false
}
];
$(document).ready(function() {
$("#calendar").fullCalendar();
});
$("#btnLoadEvents").click(function(){
$("#calendar").fullCalendar("addEventSource", source);
});
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.print.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<button type="button" id="btnLoadEvents">Load events</button>
<div id="calendar" />
Do you know if is it possible to elaborate the response before use it for the event?
Yes, get the events from your custom ajax response:
var customAjaxResponse = {"status":true,"success":true,"result":[{"id":2,"title":"test","start":"2017-07-06T10:30:00","end":"2017-07-06T11:30:00"},{"id":3,"title":"test","start":"2017-07-07T16:30:00","end":"2017-07-07T17:30:00"}],"error":null};
var source = customAjaxResponse.result;
Then add the source to the calendar:
$("#calendar").fullCalendar("addEventSource", source);
See the final result:
var customAjaxResponse = {"status":true,"success":true,"result":[{"id":2,"title":"test","start":"2017-07-06T10:30:00","end":"2017-07-06T11:30:00"},{"id":3,"title":"test","start":"2017-07-07T16:30:00","end":"2017-07-07T17:30:00"}],"error":null};
var source = customAjaxResponse.result;
$(document).ready(function() {
$("#calendar").fullCalendar();
});
$("#btnLoadEvents").click(function(){
$("#calendar").fullCalendar("addEventSource", source);
});
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.print.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<button type="button" id="btnLoadEvents">Load events</button>
<div id="calendar" />
Note: You could add events dynamically whenever you want, although other events are already present on the calendar (try to click many times on the buttons in the above example).
I hope it helps you, ciao Luca.
Updated: How to hide/show events with a specific filter:
For each single event you can check whether it's to be displayed or not, with a function on eventRender, like following:
eventRender: function (event, element, view) {
var roomId = getRoomIdFromEvent(event.id);
return $("#chkRoom" + roomId).is(':checked');
},
So, when the function returns true the event will be displayed otherwise it will be hidden.
Finally, when the filters change you have to refresh the calendar:
$(mySelector).click(function(){
$("#calendar").fullCalendar("refetchEvents");
};
See following please:
var customAjaxResponse = {"status":true,"success":true,"result":[{"id":2,"title":"test","start":"2017-07-06T10:30:00","end":"2017-07-06T11:30:00", "room": 1},{"id":3,"title":"test","start":"2017-07-07T16:30:00","end":"2017-07-07T17:30:00", "room": 2}],"error":null};
var source = customAjaxResponse.result;
$(document).ready(function() {
$("#calendar").fullCalendar({
eventRender: function (ev, el, v) {
console.log(ev);
var roomId = ev.room;
return $("#cmdRoom").val()==roomId;
}
});
$("#calendar").fullCalendar("addEventSource", source);
});
$("#cmdRoom").change(function(){
$("#calendar").fullCalendar("refetchEvents");
})
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css">
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.print.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<select id="cmdRoom">
<option value="1">Room one</option>
<option value="2">Room two</option>
</select>
<div id="calendar" />

I resolved with Fullcalendar events as a function where I can elaborate each single event field. This is my final code
success: function(doc) {
if (doc.status && doc.success && bookingForm.room){
var events = [];
var color = [];
for (index = 0; index < doc.result.length; ++index) {
//change the color if user is the owner of event
if (doc.result[index].owner == document.getElementById('username').innerHTML)
color = '#3c8dbc';
else
color = '#FF0000';
events.push({
editable: false,
id: doc.result[index].id,
title: doc.result[index].title,
start: doc.result[index].start,
end: doc.result[index].end,
color: color,
});
}
callback(events);
}
}
instead the first call to web service has done with a roomId initialize with -1 so it return no result

Related

Trigger an event when next month button clicked on fullcalendar not working

I have the following fullcalendar and it is loading current month data. This is loading correctly with all the events.
$(document).ready(function() {
var d = new Date();
var defaultMonth = d.getMonth() + 1;
var defaultYear = d.getFullYear();
$.ajax({
type: "POST",
url: "calendarChangeAjax.php",
data: {
selectedMonth: defaultMonth,
selectedYear: defaultYear
},
success: function(mainResult) {
var mainResults = JSON.parse(mainResult);
console.log(mainResults);
populateCalendar(mainResults);
}
});
});
function populateCalendar(jArray) {
var colors = "white";
var dict = [];
var details;
for (i = 0; i < jArray["start"].length; i++) {
var dates = jArray["start"][i];
if (jArray["title"][i] != null) {
details = jArray["title"][i];
colors = "#E0F8E0";
dict.push({
"title": details,
"start": dates,
"color": colors
});
}
}
jArray.length = 0;
// var todayDate = new Date();
$('#calendar').fullCalendar({
// defaultDate: todayDate,
eventLimit: true, // allow "more" link when too many events
events: dict
});
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.css" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.7/semantic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js"></script>
<div class="ui container">
<div class="ui grid">
<div class="ui sixteen column">
<div id="calendar"></div>
</div>
</div>
</div>
Following is the codes in the Ajax file calendarChangeAjax.php
$selectedMonth = $_POST['selectedMonth'];
$selectedYear = $_POST['selectedYear'];
$detailsArray = [];
$datesArray = [];
$query = "SELECT * FROM supervisorupdate WHERE MONTH(dateAdded) = '$selectedMonth' AND YEAR(dateAdded) = '$selectedYear' AND status =0";
$queryExecute = mysqli_query($conn, $query);
while ($queryExecuteResults = mysqli_fetch_array($queryExecute)) {
$oa1 = $queryExecuteResults['oa1'];
$oa2 = $queryExecuteResults['oa2'];
$dateAdded = date("Y-m-d", strtotime($queryExecuteResults['dateAdded']));
$singleDetail = $oa1.$oa2;
array_push($detailsArray, $singleDetail);
array_push($datesArray, $dateAdded);
}
$detailsDictionary = ["title" => $detailsArray];
$datesDictionary = ["start" => $datesArray];
$completedDictionary = array_merge($detailsDictionary, $datesDictionary);
echo json_encode($completedDictionary);
I want the fullcalendar to change events when I click on the next month button based on that month. So I added the following codes
$('body').on('click', 'button.fc-next-button', function() {
var selectedMonth = $('#calendar').fullCalendar('getView').intervalStart.format('MM');
var selectedYear = $('#calendar').fullCalendar('getView').intervalStart.format('YYYY');
$.ajax({
type: "POST",
url: "calendarChangeAjax.php",
data: {
selectedMonth: selectedMonth,
selectedYear: selectedYear
},
success: function(nextResult) {
var nextResults = JSON.parse(nextResult);
console.log(nextResults);
populateCalendar(nextResults);
}
});
});
I am getting nextResults correctly from Ajax call.
{title: Array(7), start: Array(7)}
But somehow, events are not showing when I click next button. It always shows only default data when fullcalendar loaded for the first time. Can someone help me on this?
Update: As pointed out in the comments (thanks #ADyson), your JS is referencing Fullcalendar v3. That's quite old now, v5 is current. My original answer referenced v5 docs, I've updated with v3 links/options as well.
Here's a super simple example. Notes:
If you don't specify an initialDate (v5), (or defaultDate in v3) it will default to the current date - so no need to set up the current date.
If you configure a JSON feed for events:, Fullcalendar will use GET to request them. If you want to use POST, you can do that, using the eventSources extended format (v5) (or v3). However, convention is that POST is for changing data (eg making a purchase, updating a record), while GET is for reading data. AFAICT you're just loading event data, which should really be a GET. I'd suggest sticking with convention and updating your back end to respond to GET instead of POST.
Fullcalendar will automatically make a new request to your event feed when it needs new data, eg when you navigate to a new month. No need to add any code to manually handle that.
JS (v5):
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
dayMaxEventRows: 3, // I think this is the v5 equivalent of eventLimit
events: 'calendarChangeAjax.php',
});
calendar.render();
});
JS (v3):
// Fullcalendar v3 with jQuery
$(document).ready(function() {
$('#calendar').fullCalendar({
eventLimit: true, // allow "more" link when too many events
events: 'calendarChangeAjax.php',
});
});
I am not sure exactly what your PHP is doing with the 2 merged result sets. But as long as you generate a JSON feed from an array that looks like this, Fullcalendar will handle it:
[
{
"title": "Event 1",
"start": "2019-09-05T09:00:00",
"end": "2019-09-05T18:00:00",
"color: "#E0F8E0"
},
{
"title": "Event 2",
"start": "2019-09-08",
"end": "2019-09-10",
"color: "#E0F8E0"
}
]
The docs describe other properties you can add to your events.

Overriding datatables.js search behavior [duplicate]

This question already has an answer here:
Odd behavior of datatables.search function after modifying it
(1 answer)
Closed 4 years ago.
There are already several questions here on SO on this subject, however none is about my exact situation.
I have a datatable with 2 columns, one contains text input field and the other a select. The current behavior of datatables' search functionality is to search in the entire select HTML. The behvior I want is search only the chosen option.
I'm aware we can override/intercept the search/filter events, ie
$('#mapping-table_filter input', data_table.table().container())
.off('.DT')
.on('keyup.DT cut.DT paste.DT input.DT search.DT', function (e) {
data_table.search(...).draw();
});
// or
data_table.on('search.dt', function () {
});
But this does not help since .search does not accept a callback.
JSFiddle
https://jsfiddle.net/0oabx2mr/
If you search for any of "first", "second" or "third" both rows are still visible. I want to be able to search for "second" and "third" and only get the relevant row.
With slight architecture changes, your example may look like that:
var srcData = [
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption'],
['firstOption', 'secondOption', 'thirdOption']
];
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: srcData,
columns: [{
title: 'Options',
render: (data, type, row) => '<select>'+row.reduce((options, option) => options += `<option value="${option}">${option}</option>`,'')+'</select>'
}]
});
var needle = null;
$.fn.DataTable.ext.search.push(
(settings, row, index) => $(dataTable.cell(`:eq(${index})`,':eq(0)').node()).find('select').val().match(needle) || !needle
);
$('#search').on('keyup', event => {
needle = $(event.target).val();
dataTable.draw();
});
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<input id="search"></input>
<table id="mytable"></table>
</body>
</html>

FullCalendar: Filtering Events That Are Multiple Types

I have events that are certain types,(for this example:) "Cats" or "Dogs", and I can filter them individually just fine, using this jquery fullcalendar event filtering .
But what I can't figure out is, how can I filter events that can be multiple types?
For example, an event is a Dog AND a Cat and another event is just Cat and Dog.
When I select Dog with my selector, only the category that is just Dog shows up. But I want the category that is Dog and Cat to show up also, because it has Dog category in it.
Here is my code I have.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">
<link href = "https://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0/jquery.qtip.min.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/qtip2/3.0.3/jquery.qtip.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.js"></script>
</head>
<script>
$(document).ready(function() {
// page is now ready, initialize the calendar..
$('#calendar').fullCalendar({
displayEventTime: false,
themeSystem: 'bootstrap4',
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
editable: false, // Don't allow editing of events
handleWindowResize: true,
//console.log((events))
events : [{start: '7/17/2018',title:"Single Type", category:"Dog"},
{start: '7/19/2018',title:"Single Type", category:"Cat"},
{start: '7/23/2018',title:"Multiple Types", category:"Cat, Dog"},
{start: '7/26/2018',title:"Multiple Type", category:"Dog, Cat"},], /**/
eventRender: function(event, element) {
element.qtip({
content: event.description + '<br />',
style: {
classes: 'qtip-green',
},
position: {
corner: {
target: 'center',
tooltip: 'bottomMiddle'
}
}
});
},
eventRender: function eventRender(event, element, view) {
return ['all', event.category].indexOf($('#type_selector').val()) >= 0
}
});
$('#type_selector').on('change',function(){
$('#calendar').fullCalendar('rerenderEvents');});
});
}
</script>
<select id="type_selector">
<option value="all">All</option>
<option value="Dog">Dog </option>
<option value="Cat">Cat</option>
</select>
<div id='calendar'></div>
Since you add "all" to your array that you are searching for index of filter value it no longer searches in your category string, but it does search in your newly formed array. For example when you filter "Dogs" the code is evaluated to:
["all", "Dog, Cat"].indexOf("Dog") >= 0 which returns false.
One way of doing what you want would look like this:
$('#type_selector').val() === 'all' || event.category.indexOf($('#type_selector').val()) >= 0
Meaning if you selected all, then we always render all events, and in other cases search of "Dog" or "Cat" occurance in event category string.
Also you might want to declare your $('#type_selector') as a variable and use that rather than getting it everytime; that would make it more efficient.

How to pass a variable to full calendar event?

this is my code
$(document).ready(function() {
var dates = "{title : 'event1',start : '2018-07-10'},{title : 'event2',start : '2010-07-18'}";
dates = JSON.parse(dates);
alert(dates);
$('#calendar').fullCalendar({
height: 450,
defaultView: 'month',
events: dates
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
<div id="calendar"></div>
I need to pass the dates variable to the full calendar event. Please help
Your JSON is invalid, as it's just a list of objects with no link between them. You can use https://jsonlint.com/ to validate your JSON strings. This is causing you to get an error when you try and parse it because you can't change a series of objects into a single variable. Your field names and values also need to be double-quoted, so you need to wrap your string in single-quotes. Besides that fullCalendar requires an array of events, and this is a valid thing to parse into a variable.
Try this:
$(document).ready(function() {
var dates = '[{"title": "event1", "start": "2018-07-10"},{"title": "event2","start": "2010-07-18"}]';
dates = JSON.parse(dates);
$('#calendar').fullCalendar({
height: 450,
defaultView: 'month',
events: dates
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
<div id="calendar"></div>
Alternatively, you could build a JavaScript object directly, if you're using JavaScript to generate the event data:
$(document).ready(function() {
var dates = [{"title": "event1", "start": "2018-07-10"},{"title": "event2","start": "2010-07-18"}];
$('#calendar').fullCalendar({
height: 450,
defaultView: 'month',
events: dates
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
<div id="calendar"></div>
You need to pass event data as an array. At the moment, you're passing an object. Instead of writing your dates in a string, just write the array manually into the events property of the constructor as follows:
$(function() {
$('#calendar').fullCalendar({
height: 450,
defaultView: 'month',
events: [
{
title: 'event1',
start: '2018-07-10'
},
{
title: 'event2',
start: '2010-07-18'
}
]
});
});
You can read more about adding events in the FullCalendar docs.
Alternatively, if you have to use the JSON.parse(), simply wrap the string in square brackets:
var dates = JSON.parse('[{"title": "event1","start": "2018-07-10"},{"title": "event2","start": "2010-07-18"}]');

Get data from Materialize CSS chips

I need to get data from Materialize CSS chips, but I don't know, how.
$('.chips-placeholder').material_chip({
placeholder: 'Stanici přidíte stisknutím klávesy enter',
secondaryPlaceholder: '+Přidat',
});
function Show(){
var data = $('.chips-placeholder').material_chip('data');
document.write(data);
}
<!-- Added external styles and scripts -->
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/js/materialize.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.7/css/materialize.min.css">
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- HTML body -->
<div class="chips chips-placeholder"></div>
<button onclick="Show()" type="button">Show</button>
So, to access to the data's chip you just have to do this:
var data = $('#id of your chips div').material_chip('data');
alert(data[0].tag);`
'0' is the index of your data (0, 1, 2 , 3, ...).
'tag' is the chip content. You can also get the id of your data with '.id'.
To get data from Materialize CSS chips, use the below code.
$('#button').click(function(){
alert(JSON.stringify(M.Chips.getInstance($('.chips')).chipsData));
});
They appear to have changed the method available in the latest version.
The documentation suggests that you should be able to access the values as properties of the object, but I’ve spent an hour looking, not getting anywhere.
Until the following happened
$('.chips-placeholder').chips({
placeholder: 'Enter a tag',
secondaryPlaceholder: '+Tag',
onChipAdd: (event, chip) => {
console.log(event[0].M_Chips.chipsData);
},
During the onChipAdd event I was able to access the event. Within this object was an array of tags.
I know this isn't the documented way, however there is only so much time a client will accept when it comes billing and I must move on.
This worked great for me
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('.chips');
var instances = M.Chips.init(elems, {
placeholder: "Ajouter des Tags",
secondaryPlaceholder: "+tag",
onChipAdd: chips2Input,
onChipDelete: chips2Input,
Limit: 10,
minLength: 1
});
function chips2Input(){
var instance = M.Chips.getInstance(document.getElementById('chip1')), inpt = document.getElementById('myInputField');
inpt.value = null;
for(var i=0; i<instance.chipsData.length; i++){
if(inpt.value == null)
inpt.value = instance.chipsData[i].tag;
else{
inpt.value += ','+instance.chipsData[i].tag; //csv
}
}
console.log('new value: ', inpt.value);
}
});
</script>

Categories

Resources