defaults not defined while using pickadate with laravel mix $.extend($.fn.pickadate.defaults, {... . - laravel-mix

I tried to mix jquery and pickadate but it says defalts not defined although it is already defined exactly.
app.js
let $, jQuery;
jQuery = window.$ = window.jQuery = $ = require('jquery/dist/jquery.min');
require([
'pickadate/lib/picker',
'pickadate/lib/picker.date',
'pickadate/lib/picker.time'
]);
require('my.js');
webpack.mix.js
let mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js/');
...
This is how it define by default of picker.date.js
DatePicker.defaults = (function (prefix) {
return {
// The title label to use for the month nav buttons
labelMonthNext: 'Next month',
labelMonthPrev: 'Previous month',
// The title label to use for the dropdown selectors
labelMonthSelect: 'Select a month',
labelYearSelect: 'Select a year',
// Months and weekdays
monthsFull: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthsShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdaysFull: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekdaysShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
...
}
}
})(Picker.klasses().picker + '__')
Picker.extend('pickadate', DatePicker)
here is the defaults that undefined
$.extend($.fn.pickadate.defaults, {
selectMonths: true, // Creates a dropdown to control month
...
});
jQuery is loaded and no prob with method $(...).
Maybe there is someone know about this ^^.
I don't know why this happen, I hope I will get a good solution here.

Sorry, its my bad, I should use 'jquery' instead of 'jquery/dist/jquery.min' to work with plugin.

Related

Laravel how to pass data into Chart.js?

I want to pass data into Chart.js, however nothing appear on the card. How to solve this problem adn what is the correct way to pass data into Chart.js? I cant directly put the data into the script in this way.
Controller
public function ViewAnalytic(){
$id = Auth::user()->id;
$electrical = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Electrical System')->count();
$pest = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Plumbing System')->count();
$plumbing = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Pest Infectations')->count();
$structural = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Structural Repairs')->count();
$appliances = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Electrical Appliances')->count();
$others = DB::table('maintenances')->where('landlord_id', $id)->where('category', 'Others')->count();
return view('analytic.analytic-page', compact('total_num', 'vacant', 'rented', 'user', 'paid', 'unpaid',
'electrical', 'pest', 'plumbing', 'structural', 'appliances', 'others'));
}
view.blade.php
<div class="card-body px-3 py-4-5">
<canvas id="myChart" width="200" height="200"></canvas>
</div>
Script
<script>
const data = {
labels: [
'Electrical System',
'Plumbing System',
'Pest Infections',
'Structural Repairs',
'Electrical Appliances',
'Others'
],
datasets: [{
label: 'My First Dataset',
data: [{!!$electrical!!}, {!!$plumbing!!}g, {!!$pest!!}, {!!$structural!!}, {!!$appliances!!}, {!!$others!!}],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(204, 102, 235)',
'rgb(255, 205, 86)',
'rgb(0, 204, 102)',
'rgb(102, 153, 255)',
'rgb(191, 0, 205)'
],
hoverOffset: 4
}]
};
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'pie',
data: data,
});
</script>
Make an ajax request in the view file, then push the values in the chart.
And you can try this
{!! json_encode($electrical) !!}
Have a look at this tutorial
https://www.codeleaks.io/ajax-get-post-request-in-laravel/
{!!$plumbing!!}g
I think that you can try removing this "g" in your data. At first look everything is correct.

Format Intl.DateTimeFormat Locale options

After some help here, some online reading, and some headaches, we have managed to get the current time of Rome and updated constantly as if it was in real-time.
Now I am trying to format the way date/time are displayed, but I cannot modify some parameters.
Here is my code:
let timer = setInterval(updateTime, 0);
function updateTime() {
const localeOptions = {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'short',
formatMatcher: 'day, month, year',
year: '2-digit'
};
const timetag = document.getElementById('timetag');
const url = "https://worldtimeapi.org/api/timezone/Europe/Rome"
fetch(url).then(r => r.json()).then(r => {
const d = new Date(r.datetime);
timetag.innerText = d.toLocaleString('it-IT', localeOptions)
});
}
Everything works until I insert the formatMatcher and the year in 2-digits. I'm following the parameters from here so I wonder what is making everything breaking?
Here the JSFiddle of the timer.
My goal is to have something like 16 APR | 14:06, or at least the closer possible to something minimal in its details and space being taken on screen.
What's wrong in the code, especially in the formatMatcher and year? They break everything ¯_(ツ)_/¯
Can you imagine any problems happening from fetch every 0 milliseconds?
You essentially have the solution, the parts just need to be assembled differently.
The localeOptions is misconfigured -
RangeError: formatMatcher must be either "basic" or "best fit"
TypeError: dateStyle and timeStyle may not be used with other DateTimeFormat options
Fixing that, we have a basic demo -
const f = new Intl.DateTimeFormat("it-IT", {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'short',
})
console.log(f.format(new Date()))
// lunedì 17 ottobre 2022, 18:08
Parts like fetch are not needed, helping us avoid costly network requests.
Now we can write the setInterval code -
const dtf = new Intl.DateTimeFormat("it-IT", {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'long',
})
setInterval(() => {
document.body.textContent = dtf.format(new Date())
}, 0)
But setInterval has issues when used in this way. A better option is requestAnimationFrame -
const dtf = new Intl.DateTimeFormat("it-IT", {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'long',
})
requestAnimationFrame(function update(frame) {
document.body.textContent = dtf.format(new Date())
requestAnimationFrame(update)
})

FullCalendar change color new event

I use fullcalendar and I need to now how to change the color of the new event, to differentiate it from the loaded events into the database. The person who puts the new event, has to difference from others by color.
The calendar uses everyone, no user control and events are stored in a database.
Your question leaves some questions of its own. Do you expect for the color of the new event to be rendered later? or is the color completely disposable and used only for differentiating between a new and old event?
Given the questions though - remember that you can set color is MANY different ways. You can set a static color for all items loaded from the database in your ajax call:
events: {
url: 'php/get-events.php',
error: function() {
$('#ajax-warning').show();
},
color: "yellow"
},
That will set the default color for all the events loaded from JSON.
In the json data itself, you can set the backgroundColor attribute to change the color of an individual item, e.g
{
"id": "999",
"title": "Repeating Event",
"start": "2016-05-09T16:00:00-05:00",
"backgroundColor": "purple"
},
You can set the event color in a form (if that is how you allow a user to create an event)
If you have a set of static events that can be added you can cycle through a list of colors and provide each one in the list with a different background.
--
If this doesn't answer your question, try poviding more information on what you have currently and what you'd like to accomplish.
/* initialize the calendar
-----------------------------------------------------------------*/
$('#calendar').fullCalendar({
events: JSON.parse(json_events),
height:447,
utc: true,
allDaySlot:false,
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
eventConstraint: {
start: moment().format('YYYY-MM-DD'),
end: '2100-01-01'
},
firstDay: 1,
monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miercoles',
'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'],
minTime:'09:00:00',
maxTime:'13:30:00',
buttonText: {
today: 'hoy',
month: 'mes',
week: 'semana',
day: 'dia'
},
eventStartEditable: false,
eventTextColor: '#AE413F',
defaultView: 'agendaWeek',
hiddenDays: [6, 0],
editable: true,
droppable:true,
eventDurationEditable:false,
slotDuration: '00:30:00',
defaultEventMinutes: 30,
defaultTimedEventDuration:'00:30:00',
forceEventDuration:true,
eventReceive: function(event){
var title = prompt('Nombre y Apellidos:');
var start = event.start.format("YYYY-MM-DD[T]HH:mm:SS");
var end = event.end.format("YYYY-MM-DD[T]HH:mm:SS");
var antena = 'ANTENA1';
var ssid = 'E18D93D0-B4B2-4802-8D04-CD2154B88A18';
if(title!=null){
$.ajax({
url: 'process.php',
data: 'type=new&title='+title+'&start='+start+'&end='+end+'&antena='+antena+'&SSID='+ssid+'&zone='+zone,
type: 'POST',
dataType: 'json',
success: function(response){
event.title = title;
$('#calendar').fullCalendar('updateEvent',event);
alert("Añadido: Atención NO marcar la casilla inferior si quiere guardar correctamente los datos");
},
error: function(e){
console.log(e.responseText);
if(error='true'){
alert('CITA YA ASIGNADA: Atención NO marcar la casilla inferior si quiere un funcionamiento correcto');
}//location.reload();
}
});}else{
location.reload();}
$('#cafireflendar').fullCalendar('updateEvent',event);
console.log(event);
//location.reload();
},

What's missing in this Kendo Grid / DropDownList combination?

Seems to be the usual problem with Kendo grids, but a dropdown being rendered into the toolbar needs to fire an Ajax request to the server and refresh the grid from the returned data. I can see in Fiddler that the Ajax call is successfully being actioned and data is definitely being returned but we're not getting anything refreshed on the grid.
Here's the View code:
<div class="grid-validation-error" id="unitgrid-validation-error">
</div>
#(Html.Kendo()
.Grid(Model)
.Name("WheelchairAlertsGrid")
.Sortable()
.Scrollable(scr => scr.Height("100%"))
.Filterable()
.ToolBar(t => t.Template(
#<text>
<div class="toolbar">
<label class="category-label" for="category">Show alerts for:</label>
#(Html.Kendo().DropDownList()
.Name("filter-periods")
.DataTextField("Text")
.DataValueField("Value")
.OptionLabel("Month")
.Events(e => e.Change("filterPeriodChange"))
.BindTo(new List<SelectListItem>(){
new SelectListItem{ Text = "Day", Value = "Day" },
new SelectListItem{ Text = "Week", Value = "Week" },
new SelectListItem{ Text = "Month", Value = "Month" } })
)
</div>
</text>
))
.Pageable(paging => paging.Messages(msg => msg.Display(ResourceManager.RetrieveResource("PagingFormat"))))
.Columns(
col =>
{
col.Bound(um => um.SerialNumber).Width(150).Title("Wheelchair").ClientTemplate
(
"<a href='" +
Url.DealerGroupAction("Index", "Wheelchair") +
"/#= WheelchairDataAssignmentId #'>#= SerialNumber #" + "</a>"
);
col.Bound(um => um.Name).Width(150);
col.Bound(um => um.ChargeAlert).Width(60);
col.Bound(um => um.BatteryAbuse).Width(60);
col.Bound(um => um.Flash).Width(60);
col.Bound(um => um.Transmission).Width(60);
col.Bound(um => um.DealerGroup).Width(100);
})
)
And here's the JS code to refresh the data (with assorted variations commented out that have also been tried but failed to yield results):
function filterPeriodChange(e) {
var ddl = $('#filter-periods').data('kendoDropDownList');
var grid = $('#WheelchairAlertsGrid').data("kendoGrid");
$.getJSON('#Url.DealerGroupWheelChairAlertsApiUrl("WheelchairAlerts")', { filterPeriod: ddl.value() }, function (data) {
grid.dataSource = data;
});
}
There's always something really simple causing these sorts of problems but I can't see the forest for the trees. Any assistance appreciated.
Cracked it.
The Kendo Grid data source needs to be told to expect Ajax content. So the code should look like the following:
... other stuff as above
.DataSource(ds => ds
.Ajax()
.PageSize(20)
)
The next piece of the puzzle is to ensure the data source is being set correctly after picking up the data:
function filterPeriodChange(e) {
var ddl = $('#filter-periods').data('kendoDropDownList');
var grid = $('#WheelchairAlertsGrid').data("kendoGrid");
$.getJSON('#Url.DealerGroupWheelChairAlertsApiUrl("WheelchairAlerts")', { filterPeriod: ddl.value() }, function (data) {
var dataSource = new kendo.data.DataSource({
data: data.Data,
pageSize: 20
});
grid.setDataSource(dataSource);
});
}
That seems to have sorted the issue. Now, changing my dropdown list at the top level calls my filterPeriodChange method, fires off an Ajax request and re-binds the data.

Asp.net MVC Telerik chart.options.series.push

my application is asp.net MVC, using Telerik MVC charts. I am trying to hide and show series using Javascript:
Here is the chart:
#(Html.Telerik().Chart<MyVDC.Models.ChartData.PatientGroupData>()
.Name("Chart")
.Title(title => title
.Text("Representative Sales vs. Total Sales"))
.Series(series =>
{
//series.Line(s => s.Diastolic).Name("Diastolic");
series.Line(s => s.Systolic).Name("Systolic");
series.Line(s => s.HeartRate).Name("Heart Rate");
})
.CategoryAxis(axis => axis
.Categories(s => s.Day).Labels(labels => labels.Template("${ formatDate(value) }"))
)
.DataBinding(dataBinding => dataBinding
.Ajax().Select("_PatientGroupChartData", "BP"))
)
Here is the script for showing Diastolic series:
function ShowDiastolic() {
var chart = $("#Chart").data("tChart");
chart.options.series.push({ color: "red", data: [chart.Diastolic], name: "Diastolic", type: "Line" });
chart.refresh();
}
I did not have any luck, I would appreciate your suggestions. Thanks in advance.
I found it should be like this:
chart.options.series.push({ color: "red", data: [11, 11, 23, 13], name: "Diastolic", type: "Line" });
Also the chart should not have any series to start with.

Resources