I have a script that separates the date from a datepicker into day, month, and year. It works fine when there is one form on the page but not when there is a second one (presumably due to the id being the same). How can I add a value to my id and name so that they are unique values?
var now = new Date();
var date = jQuery('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
date.val(today);
jQuery('form').on('submit', function() {
var newVal = date.val().split('-'),
dateParts = {
year: parseInt(newVal[0], 10),
month: parseInt(newVal[1], 10),
day: parseInt(newVal[2], 10)
};
jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) {
var name = 'date_' + key;
return jQuery('<input>', {
type: 'hidden',
name: name,
id: name,
value: dateParts[key]
});
}));
});
Need declare a variable that determines the current form:
(function ($) {
var now = new Date();
var date = $('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
date.val(today);
var form = $('form.reservation');
form.on('submit', function () {
var currentForm = $(this);
var newVal = currentForm.find('.form-date').val().split('-'),
dateParts = {
year: parseInt(newVal[0], 10),
month: parseInt(newVal[1], 10),
day: parseInt(newVal[2], 10)
};
currentForm.find('.anchor').append($.map(dateParts, function (index, key) {
console.log(['date', form.index(currentForm), key].join('_'));
return $('<input>', {
type: 'hidden',
name: ['date', key].join('_'),
id: ['date', form.index(currentForm), key].join('_'),
value: dateParts[key]
});
}));
});
})(jQuery);
Related
This is my situation; the daterangepicker is working, everything is working indeed, but there is a loop I cant find a way to avoid. Each time I choose a date range with invalid date Ive got the alert message but this never stop popping up. In fact, I found that if I hide all the code insideisInvalidDate and I just write a console.log, there is still a loop. Ive tried to take the validaterange function outside but as the variables are locals, the function doesnt work.
This is my .js:
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $(
'input[name="daterange"]'
).data("daterangepicker").startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(
temp[2],
temp[1] - 1,
temp[0]
);
if (
startDate < tempDate &&
endDate > tempDate
) {
alert("Invalid Date Range");
return false;
}
}
}
);
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I pasted a full copy but I suppose the problem should be in those lines. As youll see Im an newbie and I hope you understand my poor level of English. I've spent some time reading post but Im not really sure about this.
Thank you so much.
I've solved, Ive just been able to take the function out like this;
$(document).ready(function () {
idRoom = document.getElementById("room_name").value;
$.ajax({
url: "getData/" + idRoom,
type: "get",
dataType: "json",
success: function (response) {
var today = new Date();
var day =
today.getFullYear() +
"/" +
today.getMonth() +
+1 +
"/" +
today.getDate();
$('input[name="daterange"]').daterangepicker({
opens: "right",
drops: "up",
minDate: day,
maxSpan: {
days: 15,
},
locale: {
format: "YYYY/MM/DD",
},
isInvalidDate: function (date) {
var len = response["data"].length;
for (var i = 0; i < len; i++) {
var Str = response["data"][
i
].reservation_checkout.replace(/-/g, ","); //quitamos 1 dia al checkout para que ese dia este disponible
var newStr = new Date(Str);
newStr.setDate(newStr.getDate() - 1);
var newdate = new Date(newStr);
date[i] = newdate.toISOString().split("T")[0];
}
var dateRanges = []; //obtenemos los datos checking/checkout y los metemos en datepicker
for (var i = 0; i < len; i++) {
dateRanges.push({
start: moment(
response["data"][i].reservation_checking
),
end: moment(date[i]),
});
}
return dateRanges.reduce(function (bool, range) {
return (
bool || (date >= range.start && date <= range.end)
);
}, false);
},
});
var len = response["data"].length;
var dateRangesfix = [];
for (var i = 0; i < len; i++) {
var startDatefix = moment(
response["data"][i].reservation_checking
).format("DD-MM-YYYY");
var endDatefix = moment(
response["data"][i].reservation_checkout
).format("DD-MM-YYYY");
dateRangesfix.push(startDatefix, endDatefix);
}
$('input[name="daterange"]').on(
"apply.daterangepicker",
function validateDateRange() {
var txtStartDate = $('input[name="daterange"]').data(
"daterangepicker"
).startDate;
var txtEndDate = $('input[name="daterange"]').data(
"daterangepicker"
).endDate;
var startDate;
var endDate;
var tempDate;
if (txtStartDate == "") return false;
if (txtEndDate == "") return false;
startDate = new Date(txtStartDate);
endDate = new Date(txtEndDate);
for (i = 0; i < 2 * len; i++) {
var temp = dateRangesfix[i].split("-");
tempDate = new Date(temp[2], temp[1] - 1, temp[0]);
if (startDate < tempDate && endDate > tempDate) {
alert("Invalid Date Range");
return false;
}
}
}
);
},
});
});
$("#button1").click(function (event) {
startDate = $('input[name="daterange"]').data("daterangepicker").startDate;
var d = new Date(startDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
start_Date_fix = year + "-" + month + "-" + day;
document.getElementById("start_Date").value = start_Date_fix;
endDate = $('input[name="daterange"]').data("daterangepicker").endDate;
var d = new Date(endDate),
month = "" + (d.getMonth() + 1),
day = "" + d.getDate(),
year = d.getFullYear();
end_Date_fix = year + "-" + month + "-" + day;
document.getElementById("end_Date").value = end_Date_fix;
//calcular numero de noches
var date = $('input[name="daterange"]').val();
var str = date.split("-");
var startDate = str[0];
var startDate_f = startDate.split("/");
var startDate_fo = new Date(
startDate_f[0],
startDate_f[1] - 1,
startDate_f[2]
);
var endDate = str[1];
var endDate_f = endDate.split("/");
var endDate_fo = new Date(endDate_f[0], endDate_f[1] - 1, endDate_f[2]);
var Difference_In_Days = Math.round(
(endDate_fo - startDate_fo) / (1000 * 60 * 60 * 24)
);
var year = startDate_f[0];
var month = startDate_f[1];
var day = startDate_f[2].replace(/\s+/g, "");
var guests = document.getElementById("guests").value;
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
type: "get",
dataType: "json",
data: {},
success: function (data) {
document.getElementById("total_amount").value = data;
},
});
});
I would recommend validating the date ranges server-side with Laravel's Validation
tools and Carbon if formatting is required. Instead of using the GET method on the price calculator route:
$.ajax({
url:
"calculatePrice/" +
year +
"/" +
month +
"/" +
day +
"/" +
Difference_In_Days +
"/" +
idRoom +
"/" +
guests,
You would make a post request and use the Request $request typehint or Request facade to access incoming data and simply return the data from the calculator OR continue to use the GET method and pass the date input as a wildcard/route-parameter to.
If you require front-end validation, I would recommend using a Vue component and a package such as Vuelidate to simplify the process. In my experience, front-end validation is very time-consuming without using Vuelidate. This would be my recommendation, as there are plenty of date-picker Vue components available as well which can be configured to format on the front-end also.
(If by "alert" you meant an actual alert window and not a bootstrap component)
Sidenote: using Alerts to report validation errors is not practical and in my personal opinion, shouldn't be used. Instead, validate server-side and return error messages, check for error messages on the front end, and then display those messages near the input it's for.
It looks like you answered your own issue while I was typing this, so I'll leave it here anyway.
Hello I am trying to add increment in my all form fields from zero to the number whenever I add new clone it assigns the next number to the name tag, I tried all the ways but no any methods works for me.
Here is my fiddle
https://jsfiddle.net/o5wam5r2/
and here is my JS code
var formItem;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name="txtSchedule"]').val();
cloneForm.find('[name="txtSchedule"]').val(addOneMonth(date));
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var year = parseInt(date.split("-")[0]);
var month = parseInt(date.split("-")[1]) + 1;
var day = parseInt(date.split("-")[2]);
if(month > 12) {
month = month - 12;
year++
}
return year + "-" + month + "-" + day;
}
I fixed it by changing a little piece of code
var formItem;
var counter = 0;
$(document).ready(function() {
//Clone and remove your div instead of hiding it
formItem = $('.ScheduleextraPartTemplate').clone();
formItem.find('[name^=txtSchedule]')[0].name = "txtSchedule" + counter;
formItem.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + counter;
$('.ScheduleextraPartTemplate').remove();
formItem.addClass('clone clone-1');
$('#Schedulecontainer').append(formItem);
});
$(document).on('click', '#ScheduleaddRow', function() {
var lens = counter++;
var cloneForm = $('.clone').last().clone();
var cloneNum = $('.clone').length;
cloneForm.removeClass('clone-'+cloneNum).addClass('clone-' + (cloneNum+1));
var date = cloneForm.find('[name^="txtSchedule"]').val();
cloneForm.find('[name^="txtSchedule"]').val(addOneMonth(date));
cloneForm.find('[name^=txtSchedule]')[0].name = "txtSchedule" + (lens+1);
cloneForm.find('[name^=txtScheduleAmountPay]')[0].name = "txtScheduleAmountPay" + (lens+1);
$('#Schedulecontainer').append(cloneForm);
})
function addOneMonth(date) {
var d = new Date( date );
d.setMonth( d.getMonth( ) + 1 );
return d.getFullYear() + '-' + ("0" + ((d.getMonth() + 1))).slice(-2) + '-' + ("0" + (d.getDate())).slice(-2);
}
It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)
I have following array, there are some fields like dateofbirth in which I need to remove the time and change the format to MM-DD-YYYY.
var records = [
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000063",
},
{
"recordno":"000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000067",
},
];
How to convert date format in an array for all fields which have Date type as data type?
Are the dates in your array date objects? Do you want to convert them to strings? Then maybe this will work.
for (var i = 0; i < records.length; ++i) {
var birthDate = new Date(records[i].dateofbirth);
var newBirthDateString = ('0' + birthDate.getDate()).slice(-2) + '-'
+ ('0' + (birthDate.getMonth()+1)).slice(-2) + '-'
+ birthDate.getFullYear();
records[i].dateofbirth = newBirthDateString;
if (records[i].dateofdeath !== null) {
var deathDate = new Date(records[i].dateofdeath);
var newDeathDateString = ('0' + deathDate.getDate()).slice(-2) + '-'
+ ('0' + (deathDate.getMonth()+1)).slice(-2) + '-'
+ deathDate.getFullYear();
records[i].dateofdeath = newDeathDateString;
}
}
Please check the below code. Hope this help you!
var records = [
{
"recordno":"RF-000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000063",
},
{
"recordno":"RF-000001",
"firstname":"Bo",
"middlename":"G",
"lastname":"Dallas",
"gender":"male",
"dateofbirth":"2014-05-31T18:30:00.000Z",
"dateofdeath":null,
"_id":"538c701c84ee56601f000067",
},
];
for(var i=0;i<records.length;i++){
if(records[i].dateofbirth){
var splitDateTime = records[i].dateofbirth.split("T");
var splitDate = splitDateTime[0].split("-");
records[i].dateofbirth = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
}
}
JSFiddle URL: http://jsfiddle.net/mail2asik/YdBCq/1/
Updated:
It converts based on date field. Hope this help you!
for(var i=0;i<records.length;i++){
for( var attrName in records[i]){
if(records[i][attrName].indexOf("T") == 10){
var splitDateTime = records[i][attrName].split("T");
var splitDate = splitDateTime[0].split("-");
records[i][attrName] = splitDate[1] +"-"+ splitDate[2] +"-"+ splitDate[0];
}
}
}
JSFiddle URL: http://jsfiddle.net/mail2asik/YdBCq/3/
I have a StartDate and an ExpiryDate textbox. Both take values in the forms of 10/12/2013.
What I would like to be able to do is, when you change the StartDate textbox (whether from empty or just updating the date) the ExpiryDate textbox needs to add 1 year onto the date.
Example:
If StartDate = 10/12/2013 then ExpiryDate will automatically change to 10/12/2014.
How to do that with JS?
function MyFunc() {
MyTextBox = document.getElementById("<%= TextBox1.ClientID %>");
MyTextBox2 = document.getElementById("<%= TextBox2.ClientID %>");
var date = new Date(MyTextBox.value);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear() + 1;
MyTextBox2.value = day + "/" + month + "/" + year;
}
Try this, call the setExpiryDate() function whenever you need to set the expiration date.
function setExpiryDate() {
var txtStartDate = document.getElementById("ctrl1");
var txtExpiryDate = document.getElementById("ctrl2");
var dt = new Date(txtStartDate.value);
if (!isNaN(dt)) {
dt = dt.setYear(dt.getYear() + 1);
txtExpiryDate.value = padStr(temp.getDate()) + '/' + padStr(temp.getMonth() + 1) + '/' + temp.getFullYear().toString();
}
}
function padStr(i) {
return (i < 10) ? "0" + i : "" + i;
}
How about this:
function updateInput(value){
document.getElementsById('Yourelement').Value = value;
}
Other than that, all you need is some date parsing/string manipulation to find the correct year.