how make control validation with jquery - javascript

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

Related

How to disable click in past days fullcalendar

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")

How to filter JSON data by datepicker in Javascript?

Hello I am a newbie programmer.
I want to get data from my API with datepicker filter.This is my API URL:https://gmlews.com/api/data/?node_id=1
First, I choose the date that I want from my datepicker. And then the data will be displayed with console.log() command.
I know how to display all data, but I don't know how to display filtered data from datepicker. The filter that I made in my code doesn't work. I think my code is wrong. This is my first code: https://jsfiddle.net/estri012/2x3hmaLo/56/
$(function() {
$('input[name="datefilter"]').daterangepicker({
showDropdowns: true,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
var fromDate = picker.startDate.format('YYYY-MM-DD');
var toDate = picker.endDate.format('YYYY-MM-DD');
if (fromDate != '' && toDate != '') {
console.log(fromDate, toDate);
var endpoint = 'https://gmlews.com/api/data/?node_id=1';
$.ajax({
method: "GET",
url: endpoint,
data: {
fromDate: fromDate,
toDate: toDate
},
success: function(data) {
console.log(data);
var resultData = data.filter(function (a) {
var hitDates = a.timestamp || {};
// extract all date strings
hitDates = Object.keys(hitDates);
var hitDateMatchExists = hitDates.some(function(dateStr) {
var date = new Date(dateStr);
return date >= fromDate && date <= toDate
});
return hitDateMatchExists;
});
console.log(resultData);
} //function(data)end
}); //ajax end
} //if function end
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
}); //apply button end
}); //function end
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<ol class="breadcrumb">data from date : <input type="text" name="datefilter" value="" /></ol>
For example, I want to display all the data from 7 May until 8 May. So first, I pick 7 May to 8 May from my datepicker and then click apply. After I click apply, in the inspect element should show the data from 7 May until 8 May.
Can someone help me fix this code? Thankyou.
It solved! I am using plugin underscore.js. This is my final code: https://jsfiddle.net/estri012/2x3hmaLo/71/
$(function() {
$('input[name="datefilter"]').daterangepicker({
showDropdowns : true,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
$('input[name="datefilter"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
var startDate = picker.startDate.format('YYYY-MM-DD');
var endDate = picker.endDate.format('YYYY-MM-DD');
if (startDate != '' && endDate != '') {
console.log(startDate, endDate);
var endpoint = 'https://gmlews.com/api/data/?node_id=1';
$.ajax({
method: "GET",
url: endpoint,
data: {
startDate: startDate,
endDate: endDate
},
success: function(data){
var data = data;
var filteredDates = _.filter(data, function(data){
return (data.timestamp > startDate &&
data.timestamp < endDate)
});
console.log(filteredDates);
} //function(data)end
}); //ajax end
} //if function end
$('input[name="datefilter"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
});
}); //apply button end
}); //function end

Save values of dynamic generated HTML using javascript

I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you

Jquery form submit not working, instead get js warning 'body.scrollLeft is deprecated in strict mode' in console

I have the following code in my js file:
function PS_SL_HandleEvent()
{
$(document).ready(function() {
$('#form').removeAttr('onsubmit').submit(function(e) {
if(acceptCGV())
{
e.preventDefault();
if ($('#send_order_form input[type="radio"]:checked').val() == "")
{
resetAjaxQueries();
delSelection(1);
}
else
{
var carrierClass = $('input:radio[name="order_choose"]:checked').attr('class');
carrierClass = carrierClass.replace("carrier_","");
var radio_selector = '.delivery_options_address input[value="' + carrierClass + ',"], #carrierTable input[value="' + carrierClass + '"]';
$(radio_selector).attr('checked','checked');
resetAjaxQueries();
saveSelection(1);
}
}
else
e.preventDefault();
});
});
}
function saveSelection(is_submit)
{
$('#sendwithorder_errors').slideUp();
$('#sendwithorder_errors_list').children().remove();
//displayWaitingAjax('block', SL_RedirectTS);
//$('.SE_SubmitRefreshCard').fadeOut('fast');
var query = $.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: baseDir + 'modules/sendwithorder/ajax.php' + '?rand=' + new Date().getTime(),
data: 'method=saveSelection&' + 'order_choose=' + $('#send_order_form input[name=order_choose]:checked').val(),
dataType: 'json',
success: function(json) {
if (json.length)
{
for (error in json)
$('#sendwithorder_errors_list').append('<li>'+json[error]+'</li>');
$('#sendwithorder_errors').slideDown();
displayWaitingAjax('none', '');
}
else
{
displayWaitingAjax('none', '');
if(is_submit==1)
{
$('#form').submit();
alert("sam");
}
//$('#show_carrier, .SE_SubmitRefreshCard span').show();
//$('.SE_SubmitRefreshCard').fadeIn('fast');
//$('#SE_AjaxSuccess').show().delay(3000).fadeOut();
//location.reload(true);
}
}
});
ajaxQueries.push(query);
return false;
}
Even "sam" is alerted but the form does not submit. Instead, I get the following warning on submit:
body.scrollLeft is deprecated in strict mode. Please use 'documentElement.scrollLeft' if in strict mode and 'body.scrollLeft' only if in quirks mode.
Even though there is a javascript warning, but this should not hinder form submit.
Your form cannot be submitted since you call e.preventDefault(); at every submit.
Try reorganizing the logic in submit() to either preventDefault() and go through your checks, or do nothing and let the form be submitted.
I did it like this and the code worked:
var js_submit = false;
function PS_SL_HandleEvent() {
$(document).ready(function () {
$('#form').removeAttr('onsubmit').submit(function (e) {
if (js_submit == false) {
if (acceptCGV()) {
e.preventDefault();
if ($('#send_order_form input[type="radio"]:checked').val() == "") {
resetAjaxQueries();
delSelection(1);
} else {
var carrierClass = $('input:radio[name="order_choose"]:checked').attr('class');
carrierClass = carrierClass.replace("carrier_", "");
var radio_selector = '.delivery_options_address input[value="' + carrierClass + ',"], #carrierTable input[value="' + carrierClass + '"]';
$(radio_selector).attr('checked', 'checked');
resetAjaxQueries();
saveSelection(1);
}
} else
e.preventDefault();
}
});
});
}
function saveSelection(is_submit) {
$('#sendwithorder_errors').slideUp();
$('#sendwithorder_errors_list').children().remove();
//displayWaitingAjax('block', SL_RedirectTS);
//$('.SE_SubmitRefreshCard').fadeOut('fast');
var query = $.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: baseDir + 'modules/sendwithorder/ajax.php' + '?rand=' + new Date().getTime(),
data: 'method=saveSelection&' + 'order_choose=' + $('#send_order_form input[name=order_choose]:checked').val(),
dataType: 'json',
success: function (json) {
if (json.length) {
for (error in json)
$('#sendwithorder_errors_list').append('<li>' + json[error] + '</li>');
$('#sendwithorder_errors').slideDown();
displayWaitingAjax('none', '');
} else {
displayWaitingAjax('none', '');
if (is_submit == 1) {
js_submit = true;
$('#form').submit();
}
//$('#show_carrier, .SE_SubmitRefreshCard span').show();
//$('.SE_SubmitRefreshCard').fadeIn('fast');
//$('#SE_AjaxSuccess').show().delay(3000).fadeOut();
//location.reload(true);
}
}
});
ajaxQueries.push(query);
return false;
}

Java Script if statement not working

I have javascript function that includes few if else statements for some reason one of the statements is not working properly.
Script:
function makePayment(reservationID) {
var expirationDate = $("#expirationDate").val();
var creditCard = $("#creditcard").val();
if (creditCard.length == 16 && expirationDate.length == 4) {
var month = "";
var year = "";
month += expirationDate.charAt(0);
month += expirationDate.charAt(1);
year += expirationDate.charAt(2);
year += expirationDate.charAt(3);
var monthInt = parseFloat(month);
var yearInt = parseFloat(year);
var currect;
if (monthInt > 0 && monthInt < 13 && yearInt > 12 && yearInt < 24) {
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
if (currect == true) {
//
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function(msg) {
console.log("Paymentmade");
alert("Payment made");
//alert(CCA);
document.location = "index.jsp#reservation";
}
});
}
else if(currect === "false") {
alert("Please enter valid details. 3rd");
}
//
} else {
alert("Please enter valid details. 2nd");
}
} else {
alert("Please enter valid payment information. 1st");
}
}
I have checked in FireBug and the return value from my servlet is correct and and the console.log(responseText); displays the response in console. However for some reason this part of statement is not working and not displaying the alerts:
if (currect == true) {
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function (msg) {
console.log("Paymentmade");
alert("Payment made");
document.location = "index.jsp#reservation";
}
});
} else if (currect === "false") {
alert("Please enter valid details. 3rd");
}
Thanks in Advance!
Please make sure currect is not null or undefined and if it is not.
make a 'currect' global so it can be accessable:
var currect; //declare it here
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
then if currect is a boolean then try:
if (currect) {
//your code
} else {
//your code
}
and if it is string:
if (currect === 'true') {
//your code
} else if(currect === 'false') {
//your code
}
You have to place the currect if/else in the success function of your ajax call.

Categories

Resources