I try to disable clickable past days.
I'm using dateClick but can't pass multiple args and have error:
*Uncaught TypeError: date.format is not a function
My function:
EDIT:
Dateclick function with ajax.
Now don't know how to disable click, when past days
dateClick: function (info, jsEvent, view, date) {
let currDate = info.dateStr;
// if (moment().format('YYYY-MM-DD') === currDate || date.isAfter(moment())) {
// return false;
// } else {
//
// alert('Date: ' + currDate);
// alert('ID: ' + $('#reservation-form #select-service').val());
// }
let selectServiceVal = $('select#select-service').val();
if (!selectServiceVal) {
alert('Najpierw wybierz usługę');
} else {
dateValue.val(currDate);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: getFreeHorus + selectServiceVal + '/' + currDate,
dataType: 'json',
method: "POST",
data: {
"id": selectServiceVal,
"date": currDate
},
beforeSend: function () {
$(".calendary-loader").css('display', 'block');
},
success: function (data) {
$(".calendary-loader").css('display', 'none');
if (data.message) {
alert('Wybierz poprawną datę')
}
displayHours(data.availableHours);
},
error: function () {
$(".calendary-loader").css('display', 'none');
alert('Błąd serwera, spróbuj później')
}
});
}
}
You can use select. This is how I did mine:
select: this.handleDateClick.bind(this),
//the handleDateClick funtion
handleDateClick(arg: any) {
let todaysDate = new Date();
let formattedDate = moment(todaysDate).format("YYYY-MM-DDTHH:mm:ss"); //formatted version of todays date so a comparison can be made
let s1 = arg.startStr;
let s2 = arg.endStr;
let currentdate = moment().isUTC();
let newDateObj = moment(s1).add(15, "m").format("YYYY-MM-DDTHH:mm:ss");
if (s1 < formattedDate) {
//This checks if time is in the past. If so,
alert("This date is in the past")
Related
I have a Dynamic Grid in the ASP.NET page. When I click Add User, it creates an empty record with Textbox controls and when the user types something in the first Textbox - UserName, it should pull the UserNames from the Database and autocomplete should work for that Textbox control.
I have implemented jQuery.autocomplete function as below.
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
success: function (data) {
switch (data) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
var rows = data.split("|");
var jsStr = "var datalist=[";
for (i = 0; i < rows.length - 1; i++) {
var s = rows[i].toString();
s = s.replace("'", "\\'");
s = s.replace('"', "\\'");
var row = s.split("~");
jsStr += "{id:'" + row[0].toString() + "'";
jsStr += ",name:'" + row[1].toString() + "'},";
}
jsStr = jsStr.slice(0, jsStr.length - 1);
jsStr += "];";
eval(jsStr);
if (typeof (datalist) != 'undefined') {
response(jQuery.map(datalist, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
When I try to Debug this autocomplete, the data is coming at the end of response(jQuery.map(datalist, function (items) statement. But the select: option is not firing.
EDIT
The below screenshot shows how the data is formed.
And this is what is present in the Server-Side Users.aspx.vb Page_Load Event
Response.Clear()
Response.Write(GetUserName(Request.QueryString("UserName")))
Response.End()
What could be the problem?
First. In the response, you check the data variable in swith. And you get it as a string.
Second. the best way to work with ajax is JSON.
jQuery.ajax({
url: url,
dataType: 'json'
On successful response:
Make parsing.
json = JSON.parse(data)
And then you already apply your logic, I work with individual object variables.
swith(json.string){ .... }
And it will be easier to fill Textbox controls with the necessary parameters: json.user - the variable will contain an array of data about users.
Update code:
jQuery("#" + e.id).autocomplete({
source: function (request, response) {
var txtSearch = jQuery("#" + e.id).attr("id");
var t = jQuery("#" + txtSearch).val();
var URL = "../Users.aspx?UserName=" + t;
jQuery.ajax({
url: URL,
dataType: 'json',
/*
* format respone data (string!!!) -> {"result": [{"id": 1,"item": 2},{"id": 1,"item": 2}],"found": "VALUESFOUND"}
*/
success: function (data) {
let json = JSON.parse(data);
switch (json.found) {
case 'NOVALUESFOUND':
var rftspanID = e.id.replace("txt", "span");
break;
default:
var rftspanID = e.id.replace("txt", "span");
response(jQuery.map(json.result, function (items) {
if (items.id != undefined) {
return {
value: items.name,
id: items.id
}
}
}));
}
}
});
},
minlength: 1,
select: function (event, ui) {
if (Type == 1) {
document.getElementById("txtUser" + MemCount).value = ui.item.value;
}
else if (Type == 2) {
document.getElementById("txtRole" + MemCount).value = ui.item.value;
}
},
open: function () {
jQuery(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function (event) {
jQuery(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I have a function Checkdate. I want to connect this function to a save button when the user addss an event.
If the date exists, the save button shouldn't work:
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
SaveEvent(data);
// call function for submit data to the server
})
This is my function:
$('#btnSave').click (function () {
var StartDate = $('#txtStart').val();
$.ajax({
type: "POST",
url: "/Home/Checkdate",
data: '{StartDate: "' + StartDate + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var message = $("#message");
if (response) {
//Email available.
message.css("color", "green");
message.html(" date is not exist ");
}
else {
//Email not available.
message.css("color", "red");
message.html("date existe ");
}
}
});
});
function ClearMessage() {
$("#message").html("");
}
I hope you look at this image to understand me:
enter image description here
I'm making site in which I have to add some element but only when they contain class .addEvent but when I try document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")
It shows me this error in console (json[i].date is something like: 2019-11-06):
TypeError: document.getElementsByClassName(...).classList is undefined
And when I display date in console it shows as it should be.
Here is my whole javascript code, maybe it would help:
$(() => {
var event;
$.ajax({
type: "GET",
url: "getEvents.php",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function(json) {
for (var i = 0; i < json.length; i++) {
console.log(document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"));
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent")) {
document.getElementsByClassName(json[i].date)[0].innerHTML += " <br/><span class='event'>" + json[i].name + "<br/>" + json[i].place + "</span>";
document.getElementsByClassName(json[i].date)[0].style.backgroundColor = json[i].color;
document.getElementsByClassName(json[i].date)[0].style.color = "#ffffff";
document.getElementsByClassName(json[i].date)[0].style.fontWeight = "bold";
document.getElementsByClassName(json[i].date)[0].style.opacity = "0.6";
}
}
},
error: function(error) {
alert("error");
console.log(error);
}
});
var day;
var shown = false;
$("td.addEvent").click(function() {
if (shown == false) {
$(".addEventMenu").css("display", "block");
day = getDay($(this));
var clickedDay = document.getElementsByTagName("p");
clickedDay[1].innerHTML += day;
shown = true;
}
});
function getDay(input) {
return input.clone().children().remove().end().text();
}
$("button.addEventBtn").click(function(e) {
e.preventDefault();
var year;
var month = $(".month").val();
const regex = /[0-9]{4}/gm;
let m;
while ((m = regex.exec($(".date").text())) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
year = `${match}`;
});
}
var name = $(".eventName").val();
var description = $(".eventDescription").val();
var place = $(".eventPlace").val();
var startHour = $('.eventStartHour').val();
var endHour = $('.eventEndHour').val();
var color = $('.eventColor').val();
var userId = $('input.userId').val();
if (day < 10) {
day = "0" + day;
}
var date = year + "-" + month + "-" + day;
$.ajax({
url: 'addEvent.php',
data: {
'eventName': name,
'eventDescription': description,
'eventPlace': place,
'eventStartHour': startHour,
'eventEndHour': endHour,
'eventColor': color,
'eventDate': date,
'userId': userId
},
type: 'post',
success: function(data) {
},
error: function(request, status, error) {
alert(request, status);
}
});
});
$("p.closeEventMenu").click(function() {
$(".addEventMenu").css("display", "none");
var clickedDateDay = $("p.clickedDay").text();
clickedDateDay = clickedDateDay.replace(/\s+$/, '');
$("p.clickedDay").text(clickedDateDay.substring(0, clickedDateDay.length - 2));
shown = false;
});
});
You are not confirming that the element exists before trying to use it.
if (document.getElementsByClassName(json[i].date)[0].classList.contains("addEvent"))
If no elements matching class json[i].date exist, this if will throw the exception.
You should confirm the selector is returning elements before trying to use any of them:
var elements = document.getElementsByClassName(json[i].date);
if(elements.length > 0 && elements[0].classList.contains("addEvent"))
This will confirm the element actually exists before attempting to gather any information (classList) from the element. Of course, whether or not the element exists depends on many other factors - but in this case it seems that there are not any elements matching the selector on the page.
function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */
I have such code. The main problem is that var jsonOfLog = JSON.stringify(data); gives correct JSON "[{"name":"Jhon"},{"name":"Nick"},{"name":"Sanders"}]" but var jsonOfLog = JSON.stringify(test); gives undefined.
Why? It's problem with types or something else? How to fix this?
function AppViewModel() {
self = this;
self.items = ko.observableArray();
self.addItems = function () {
self.items.push({ Name: 'Test', Date: 'Test', Time: 'Test'});
}
function time_format(d) {
hours = format_two_digits(d.getHours());
minutes = format_two_digits(d.getMinutes());
seconds = format_two_digits(d.getSeconds());
return hours + ":" + minutes + ":" + seconds;
}
function format_two_digits(n) {
return n < 10 ? '0' + n : n;
}
self.save = function () {
data = [{ name: 'Jhon' }, { name: 'Nick' }, { name: 'Sanders' }];
var test = self.items;
var jsonOfLog = JSON.stringify(test);
debugger;
$.ajax({
type: 'POST',
dataType: 'text',
url: "ConvertLogInfoToXml",
data: "jsonOfLog=" + jsonOfLog,
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
}
self.capitalizeLastName = function () {
debugger;
var date = $("#date").val();
$.ajax({
cache: false,
type: "GET",
url: "GetByDate",
data: { "date": date },
success: function (data) {
var result = "";
$.each(data, function (id, item) {
var tempDate = new Date();
var tempTime = item.Time;
debugger;
tempDate =new Date(parseInt(item.Date.replace("/Date(", "").replace(")/", ""), 10));
self.items.push({ Name: item.Name, Date: (tempDate.getMonth() + 1) + '/' + tempDate .getDate() + '/' + tempDate.getFullYear(), Time: tempTime.Hours });
});
},
error: function (response) {
debugger;
alert('eror');
}
});
}
}
ko.applyBindings(new AppViewModel());
I see a couple things in your code that could be causing the problem.
First, the test variable is a reference to self.items, which is a Knockout observableArray and not a native JavaScript array. I'm not very familiar with Knockout, but that may not serialize as an array.
Also, on the first line of your constructor function, you are assigning to self without using var. This is assigning a value to a global variable instead of a local. If you have a similar construct elsewhere in your code, it is likely that the self reference is getting overwritten.
You can't stringify an observable array like that; you end up stringifying the function and not the array. You should be using the ko.toJSON(viewModel) function for that.
Remember, in KnockOut, you always need to use the object.myObservableValue() to access the actual value of the observable (instead of object.myObservableValue), otherwise you end up using the function instead of the value.