How can I dynamically insert dates in dncalendar? - javascript

I've got a problem using dncalendar, hope someone will help me!
I need a simple calendar in which being able to save and recover data from a db. dncalendar seemed good, but I have now problem in dynamically insert data into it.
I post some code for clarification. I recover the dates from some input fields called .date-smart and build an array (data_note). Problem is when I want to dynamically insert this dates into object notes, without knowing how many dates I have. If I do it like in below code, everything works fine, but I do not know how to do it with a for cycle or similar. Can someone help me?
var data_note =[];
var note = [];
$(".date-smart").each(function(){
data_note.push($(this).val())
note.push("SW");
})
var my_calendar = $("#dncalendar-container").dnCalendar({
dataTitles: { defaultDate: 'default', today : 'Today' },
startWeek:'monday',
});
my_calendar.build();
my_calendar.update({
notes: [{'date': data_note[0], 'note':note[0]}, {'date': data_note[1], 'note':note[1]}];
})

Why don't just make a variable feed all data in it and then pass it to notes
Like
var data_note =[];
var note = [];
var notesArr = [];
$(".date-smart").each(function(){
data_note.push($(this).val())
note.push("SW");
notesArr.push({'date': $(this).val(), 'note': 'SW'});
})
var my_calendar = $("#dncalendar-container").dnCalendar({
dataTitles: { defaultDate: 'default', today : 'Today' },
startWeek:'monday',
});
my_calendar.build();
my_calendar.update({
notes: notesArr
})

Related

How add new values in drop-down list using plugin "selectory" jquery

I need some help. How can I add new values in code to the list if I use a plugin from jquery. I wrote this code, but the list is empty, although the values are passed to the view. This is probably due to the fact that I am referring to the id of the div tag, but the plugin did not work differently. Help please
<html>
<main>
<form action="#">
<div class="form-group col-xs-12 col-sm-4" id="example-2"> </div>
</form>
</main>
<script>
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
function addOption() {
var ul = document.getElementById("#example-2");
for (var item in #ViewBag.List)
{
var value = item;
}
var newOption = new Option(value, value);
ul.options[ul.options.length] = newOption;
}
</script>
</html>
result of code from answer 1
The documentation of the selectivity library covers how to add new options to the dropdown.
The main issue you have is that the output from #ViewBag.List won't be in a format that JS can understand. I would suggest formatting it as JSON before outputting it to the page, then the JS can access this as a standard object, though which you can loop.
// initialisation
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
// add options, somewhere else in your codebase...
const $list = $('#example-2')
const options = #Html.Raw(Json.Encode(ViewBag.List));
options.forEach((option, i) => {
$list.selectivity('add', { id: i, text: option })
});
Note that for this to work the JS code which reads from the ViewBag needs to be placed somewhere the C# code will be executed, ie. in a .cshtml file, not in a .js file.

How to change the display format on a P13nItem TimePicker/DatePicker?

I'm trying to change the display format on the DatePicker/TimePicker used by the sap.m.P13nItem when the selected column type is date/time.
I have tried changing the aggregation P13nItem from the P13nFilterPanel in order to include the property formatSettings, but it didn't work.
Here is a sample of my XML view code.
<P13nFilterPanel id="filterPanel" visible="true" type="filter" containerQuery="true" items="{
path: 'SchedulingFilter>/ColumnCollectionFilter'
}" filterItems="{
path: 'SchedulingFilter>/FilterItems'
}">
<P13nItem columnKey="{SchedulingFilter>columnKey}" text="{SchedulingFilter>label}" type="{SchedulingFilter>type}" maxLength="{SchedulingFilter>maxLength}" formatSettings="{SchedulingFilter>formatSettings>" />
<filterItems>
<P13nFilterItem columnKey="{SchedulingFilter>keyField}" operation="{SchedulingFilter>operation}" value1="{SchedulingFilter>value1}" value2="{SchedulingFilter>value2}" exclude="{SchedulingFilter>exclude}" />
</filterItems>
</P13nFilterPanel>
Here is an extract of how I'm filling the bound data.
$.each(columnsKeys, function (i, item) {
const columnData = {};
const columnDescriptionItem = columnDescription[item];
columnData.columnKey = item;
columnData.text = columnDescriptionItem.label;
columnData.type = columnDescriptionItem.type;
columnData.formatSettings = {
pattern: 'yyyy/MM/dd',
UTC: false
};
columnData.maxLength = columnDescriptionItem.maxLength;
columnData.visible = columnDescriptionItem.visible;
columnData.index = columnDescriptionItem.index;
columnData.isEditable = columnDescriptionItem.isEditable;
columnData.isFilter = columnDescriptionItem.isFilter;
columnData.isSorter = columnDescriptionItem.isSorter;
columnsData.push(columnData);
});
The default behavior of the control displays the time/date fields as:
https://ibb.co/JcJJZhJ.
Edit: I discovered that the default behavior is based on the user's locale. I'm not considering the user's locale to change the display format on the others parts of my application.
I want to achieve, for example, the display formats "yyyy/MM/dd" and "hh:mm:ss" on these fields.
I had to extend the P13nConditionPanel (this one is responsible for the time/date components instantiation) and the P13nFilterPanel (it creates the P13nConditionPanel) on version 1.44.6 of SAPUI5 in order to solve this problem. I only had to add the necessary parameters to the DatePicker and TimePicker constructors (as shown below).
case "date":
oConditionGrid.oFormatter = sap.ui.core.format.DateFormat.getDateInstance();
params.displayFormat = DateFormatter.displayFormat();
oControl = new sap.m.DatePicker(params);
break;
case "time":
oConditionGrid.oFormatter = sap.ui.core.format.DateFormat.getTimeInstance();
params.displayFormat = TimeFormatter.getDisplayFormat();
oControl = new sap.m.TimePicker(params);
I posted my customized extended components code on pastebin:
Customized P13nConditionPanel
Customized P13nFilterPanel
I will later open an enhancement request on openui5 Github.

Iterating through rows in DataTables using JavaScript

Essentially the problem is that I am getting duplicate results in my DataTable.
In my application, the user will enter a value and that value will return an array of objects from the database and those records will then populate in the DataTable. Currently the issue that I am having is that all the records that are in the table are all the same.
There should be 100 different records in the DataTable, instead there is 100 of the exact same record. I am not seeing any examples that show how to iterate though an array of objects from a database, in a way that in can be handled by the DataTable.
I should be able to use rows.add() but that does not have anything displaying in the table and the other option I saw was rows().every() which does not have an example similar to what I am doing.
Any references, resources or insight will be very helpful. Thanks!
User Input:
<p> Year: <input id="YearNbrId" type="text" th:field="*{YearNbr}" /> </p>
Button:
<input type="button" value="Locate" id="goToDetails" />
JavaScript Snippet:
$(document).ready(function() {
var table = $('#Orders').DataTable();
$('#goToDetails').on('click', function() {
var YearNbr = $('#YearNbrId').val();
var url = './eData/locate?YearNbr=' + YearNbr;
$.get(url, function(result) {
console.log(result);
for (var i = 0; i < result.length; i++) {
var myOrder = result[i];
table.row.add([
null, // place holder
myOrder.yearNbr,
myOrder.orderNm,
'<input>', // user input
myOrder.model,
new Date(myOrder.Date).toJSON().slice(0, 10),
myOrder.srcCode,
null,
'<input>'
]).draw(false)
.nodes()
.to$();
}
});
});
});
You might want to check out the JQuery .each function. You probably need to do something like: $(result).each(function(i,obj) {//code here}); Where i is the position in the array and obj is the current record in result.

Saving table data to HTML5 LocalStorage

I've created a JSFiddle Here
What I'm trying to do is save table data from the following code:
$('#save').click(function () {
$("#dataTable").find('tbody')
.append($('<tr>')
.append($('<td>')
.text($('#fname').val()))
.append($('<td>')
.text($('#lName').val()))
.append($('<td>')
.text($('#mId').val()))
);
$('#fname').val('');
$('#lName').val('');
$('#mId').val('');
})
I would like to save the <tr> data, but I'm having trouble finding where to start on parsing that into a savable format.
I have written little bit code to help you.
First create a class for the record which you want to store in grid
function MemberInfo(fName,lName,memberId){
this.FirstName=fname;
this.LastName=lName;
this.MemberId=memberId;
}
the create a function which will loop through all the tr and tds to populate that array, and finally save the JSON data in localStorage
var arr=[];
$("#dataTable").find('tbody tr').each(function(index,item){
var fName=$(item).find('td').eq(0).text();
var lName=$(item).find('td').eq(1).text();
var memberId=$(item).find('td').eq(2).text();
arr.push(new MemberInfo(fName,lName,memberId))
});
localStorage.setItem("memberData",arr);
Fiddle
Maybe you can save it as a JSON string
var data = {
name : $('#fname').val(),
lastname : $('#lName').val(),
memberId : $('#mId').val()
};
localStorage.setItem('member-data', JSON.stringify(data))
then later:
var data = JSON.parse(localStorage.getItem('member-data') || {})
$('#fname').val(data.name);
$('#lName').val(data.lastName);
$('#mId').val(data.memberId);

Having issues tying together basic javascript chat page

I have the skeleton of a chat page but am having issues tying it all together. What I'm trying to do is have messages sent to the server whenever the user clicks send, and also, for the messages shown to update every 3 seconds. Any insights, tips, or general comments would be much appreciated.
Issues right now:
When I fetch, I append the <ul class="messages"></ul> but don't want to reappend messages I've already fetched.
Make sure my chatSend is working correctly but if I run chatSend, then chatFetch, I don't retrieve the message I sent.
var input1 = document.getElementById('input1'), sendbutton = document.getElementById('sendbutton');
function IsEmpty(){
if (input1.value){
sendbutton.removeAttribute('disabled');
} else {
sendbutton.setAttribute('disabled', '');
}
}
input1.onkeyup = IsEmpty;
function chatFetch(){
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
method: "GET",
success: function(data){
$(".messages").clear();
for(var key in data) {
for(var i in data[key]){
console.log(data[key][i])
$(".messages").append("<li>"+data[key][i].text+"</li>");
}
}
}
})
}
function chatSend(){
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input1.draft').val()}),
success:function(message){
}
})
}
chatFetch();
$("#sendbutton").on('click',chatSend());
This seems like a pretty good project for Knockout.js, especially if you want to make sure you're not re-appending messages you've already sent. Since the library was meant in no small part for that sort of thing, I think it would make sense to leverage it to its full potential. So let's say that your API already takes care of limiting how many messages have come back, searching for the right messages, etc., and focus strictly on the UI. We can start with our Javascript view model of a chat message...
function IM(msg) {
var self = this;
self.username = ko.observable();
self.message = ko.observable();
self.timestamp = ko.observable();
}
This is taking a few liberties and assuming that you get back an IM object which has the name of the user sending the message, and the content, as well as a timestamp for the message. Probably not too far fetched to hope you have access to these data elements, right? Moving on to the large view model encapsulating your IMs...
function vm() {
var self = this;
self.messages = ko.observableArray([]);
self.message = ko.observable(new IM());
self.setup = function () {
self.chatFetch();
self.message().username([user current username] || '');
};
self.chatFetch = function () {
$.getJSON("https://api.parse.com/1/classes/chats", function(results){
for(var key in data) {
// parse your incoming data to get whatever elements you
// can matching the IM view model here then assign it as
// per these examples as closely as possible
var im = new IM();
im.username(data[key][i].username || '');
im.message(data[key][i].message || '');
im.timestamp(data[key][i].message || '');
// the ([JSON data] || '') defaults the property to an
// empty strings so it fails gracefully when no data is
// available to assign to it
self.messages.push(im);
}
});
};
}
All right, so we have out Javascript models which will update the screen via bindings (more on that in a bit) and we're getting and populating data. But how do we update and send IMs? Well, remember that self.message object? We get to use it now.
function vm() {
// ... our setup and initial get code
self.chatSend = function () {
var data = {
'user': self.message().username(),
'text': self.message().message(),
'time': new Date()
};
$.post("https://api.parse.com/1/classes/chats", data, function(result) {
// do whatever you want with the results, if anything
});
// now we update our current messages and load new ones
self.chatFetch();
};
}
All right, so how do we keep track of all of this? Through the magic of bindings. Well, it's not magic, it's pretty intense Javascript inside Knockout.js that listens for changes and the updates the elements accordingly, but you don't have to worry about that. You can just worry about your HTML which should look like this...
<div id="chat">
<ul data-bind="foreach: messages">
<li>
<span data-bind="text: username"></span> :
<span data-bind="text: message"></span> [
<span data-bind="text: timestamp"></span> ]
</li>
</ul>
</div>
<div id="chatInput">
<input data-bind="value: message" type="text" placeholder="message..." />
<button data-bind="click: $root.chatSend()">Send</button>
<div>
Now for the final step to populate your bindings and keep them updated, is to call your view model and its methods...
$(document).ready(function () {
var imVM = new vm();
// perform your initial search and setup
imVM.setup();
// apply the bindings and hook it all together
ko.applyBindings(imVM.messages, $('#chat')[0]);
ko.applyBindings(imVM.message, $('#chatInput')[0]);
// and now update the form every three seconds
setInterval(function() { imVM.chatFetch(); }, 3000);
});
So this should give you a pretty decent start on a chat system in an HTML page. I'll leave the validation, styling, and prettifying as an exercise to the programmer...

Categories