detect when 2 calendar values changed - javascript

I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});

try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>

I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});

What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}

Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}

Related

Open a materialize modal not working with if codition

I want to open a modal window when some conditions are met. I looked for some code and tried to implement it however, it does not work for me.
I have a If condition also in place could that be the reason?
Complete JS code:
<script>
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
document.getElementById('btn').addEventListener('click',dostuff);
function dostuff() {
var userinfo = {};
userinfo.firstname = document.getElementById('nm').value;
userinfo.email = document.getElementById('mail').value;
userinfo.process = document.getElementById('process').value;
if (userinfo.firstname == "" || userinfo.email == "" || userinfo.process == "Choose your option"){
alert("Hello, \n\nAll Fields are required.\n\nPlease Select all the Fields.");
} else {
google.script.run.userClicked(userinfo);
document.getElementById('nm').value = "";
document.getElementById('mail').value = "";
var selc = document.getElementById('process')
selc.selectedIndex = 0;
M.FormSelect.init(selc);
document.addEventListener('DOMContentLoaded', function () {
var Modalelem = document.querySelector('.modal');
var instance = M.Modal.init(Modalelem);
instance.open();
});
}
}
Please focus on the below mentioned code as this is my real concern:-
document.addEventListener('DOMContentLoaded', function () {
var Modalelem = document.querySelector('.modal');
var instance = M.Modal.init(Modalelem);
instance.open();

How to call function of JS added in header?

I have following JS which is added in header. I have button in page. I want to call "FulfillOrder" function of JS.
I don't know how to call it.
Can anybody please suggest me how can I call?
JS:
/// <reference path='../../../../ClientCommon/Sales_ClientCommon.d.ts' />
/// <reference path="../../../../../../TypeDefinitions/CRM/ClientUtility.d.ts" />
/// <reference path='../../../../CommandBarActions/SalesCommandBarActions.d.ts' />
var Sales;
(function (Sales) {
var SalesOrderRibbonActionsLibrary = (function () {
function SalesOrderRibbonActionsLibrary() {
var _this = this;
this.CloseOrFulfillOrder = function (closedState) {
var options = { height: 350, width: 475, position: 1 /* center */ };
options.width = 330;
options.height = 400;
var dialogParams = {};
dialogParams[Sales.MetadataDrivenDialogConstantsOrderClose.SalesId] = Xrm.Page.data.entity.getId();
dialogParams[Sales.MetadataDrivenDialogConstantsOrderClose.ClosedState] = closedState;
Xrm.Navigation.openDialog(Sales.DialogName.CloseOrder, options, dialogParams).then(_this.salesOrderDialogCloseCallback);
};
this.salesOrderDialogCloseCallback = function (response) {
var parameters = response.parameters;
var lastButtonClicked = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.LastButtonClicked];
if (ClientUtility.DataUtil.isNullOrUndefined(lastButtonClicked) || lastButtonClicked.toString() !== ClientUtility.MetadataDrivenDialogConstants.DialogOkId) {
return;
}
var salesOrderId = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.SalesId];
var date = new Date(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Date]);
var closedState = parseInt(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.ClosedState]);
var reason = parseInt(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Reason]);
var description = null;
if (!ClientUtility.DataUtil.isNullOrUndefined(parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Description])) {
description = parameters[Sales.MetadataDrivenDialogConstantsOrderClose.Description].toString();
}
if (!ClientUtility.DataUtil.isNullOrUndefined(date) && !ClientUtility.DataUtil.isNullOrUndefined(date)) {
_this.commandBarActions.PerformActionAfterCloseOrder(reason, date, description, closedState, salesOrderId);
}
};
/**
* Processes the sales order.
*/
this.ProcessOrder = function () {
if (Xrm.Page.ui.getFormType() !== 4 /* Disabled */ && Xrm.Page.ui.getFormType() !== 3 /* ReadOnly */) {
Xrm.Page.data.save().then(function (successResponse) {
_this.processOrderSuccessResponse();
}, ClientUtility.ActionFailedHandler.actionFailedCallback);
}
else {
_this.processOrderSuccessResponse();
}
};
this.processOrderSuccessResponse = function () {
var columns = new ODataContract.ColumnSet(false, ["invoiceid"]);
if (!_this.IsBackOfficeInstalled()) {
var convertSalesOrderToInvoiceRequest = new ODataContract.ConvertSalesOrderToInvoiceRequest();
convertSalesOrderToInvoiceRequest.SalesOrderId = { guid: Xrm.Page.data.entity.getId() };
convertSalesOrderToInvoiceRequest.ColumnSet = columns;
Xrm.WebApi.online.execute(convertSalesOrderToInvoiceRequest).then(function (response) {
response.json().then(function (jsonResponse) {
var invoiceId = jsonResponse.invoiceid;
Xrm.Utility.openEntityForm(Sales.EntityNames.Invoice, invoiceId, null);
});
}, ClientUtility.ActionFailedHandler.actionFailedCallback);
}
else {
var defaultStatusCode = -1;
XrmCore.Commands.Common.setState(Xrm.Page.data.entity.getId(), Xrm.Page.data.entity.getEntityName(), Sales.SalesOrderState.Submitted, defaultStatusCode);
}
};
this.IsBackOfficeInstalled = function () {
// var isBackOfficeInstalled: string = Xrm.Internal.getResourceString("IS_BACKOFFICE_INSTALLED");
// if (ClientUtility.DataUtil.isNullOrEmptyString(isBackOfficeInstalled)) {
// return false;
// }
// return isBackOfficeInstalled === "1";
//TODO: investigate backoffice.
return false;
};
this.GetProductsForOrder = function () {
_this.commandBarActions.getProducts();
};
this.LockSalesOrder = function () {
debugger;
_this.commandBarActions.lock();
};
this.UnlockSalesOrder = function () {
debugger;
_this.commandBarActions.unlock();
};
this.CloseOrder = function () {
_this.CloseOrFulfillOrder(Sales.SalesOrderState.Canceled);
};
this.FulfillOrder = function () {
_this.CloseOrFulfillOrder(Sales.SalesOrderState.Fulfilled);
};
this.IsSalesOrderActive = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Active);
};
this.IsSalesOrderFulfilled = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Fulfilled);
};
this.IsSalesOrderSubmitted = function () {
return _this.IsSalesOrderState(Sales.SalesOrderState.Submitted);
};
this.IsSalesOrderState = function (state) {
var stateCodeControl = Xrm.Page.data.entity.attributes.get("statecode");
var orderState = stateCodeControl ? stateCodeControl.getValue() : null;
var returnValue = false;
if (ClientUtility.DataUtil.isNullOrUndefined(orderState)) {
return returnValue;
}
switch (state) {
case 0:
if (orderState === 0) {
returnValue = true;
}
break;
case Sales.SalesOrderState.Submitted:
if (orderState === Sales.SalesOrderState.Submitted) {
returnValue = true;
}
break;
case Sales.SalesOrderState.Fulfilled:
if (orderState === Sales.SalesOrderState.Fulfilled) {
returnValue = true;
}
break;
case Sales.SalesOrderState.FulfilledOrActive:
if (orderState === Sales.SalesOrderState.Fulfilled || orderState === 0) {
returnValue = true;
}
break;
default:
returnValue = false;
break;
}
return returnValue;
};
}
Object.defineProperty(SalesOrderRibbonActionsLibrary.prototype, "commandBarActions", {
get: function () {
if (ClientUtility.DataUtil.isNullOrUndefined(this._commandBarActions)) {
this._commandBarActions = new Sales.SalesCommandBarActions();
}
return this._commandBarActions;
},
enumerable: true,
configurable: true
});
return SalesOrderRibbonActionsLibrary;
}());
Sales.SalesOrderRibbonActionsLibrary = SalesOrderRibbonActionsLibrary;
})(Sales || (Sales = {}));
/**
* #license Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// <reference path="../../../../../TypeDefinitions/CRM/ClientUtility.d.ts" />
/// <reference path="UCI/SalesOrderRibbonActionsLibrary.ts" />
/// <reference path="../../../../../../references/internal/TypeDefinitions/XrmClientApi/XrmClassicWebClientApi.d.ts" />
var Sales;
(function (Sales) {
var SalesOrderRibbonActions = (function () {
function SalesOrderRibbonActions() {
}
return SalesOrderRibbonActions;
}());
SalesOrderRibbonActions.Instance = new Sales.SalesOrderRibbonActionsLibrary();
Sales.SalesOrderRibbonActions = SalesOrderRibbonActions;
})(Sales || (Sales = {}));
//# sourceMappingURL=SalesOrderRibbonActions.js.map
Previous version of this JS have function "fulfillOrder" and it was working properly. But in this version, they updated a lot. I don't know how to call it.
Please suggest.
Thank you.
If you are calling the methods outside then create an instance and call that FulfillOrder method,
var obj = new Sales.SalesOrderRibbonActionsLibrary();
obj.FulfillOrder(); // now call the methods
You need to call in the way mention below.
Sales.SalesOrderRibbonActionsLibrary.FulfillOrder();

insert a function inside an event jquery

i'm trying to insert a function inside this jquery event. This is the event
$(":checkbox").on('change', function() {
$.fn.myFunction();
})
and this is myFunction
$.fn.myFunction = function() {
alert('ciao');
if ($(this).is(':checked')) {
InputInserireInput = $(this).parent().parent().parent().find('.inserirePrezzoDiv');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).find('button').css('background-color','#c31432')
var checkbox = $(this);
InputInserireInput.removeClass('hidden');
var checkboxSelected = $(this).attr('id');
var nomeServizio = ($(this).next('label').text());
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', 'black')
$(this).closest('div').parent().parent().find('button').css('margin-top', -50)
var titleLabel = $(this).closest('div');
var titleSelect = $(titleLabel).parent().parent().find('.titoloPiega');
var option1 = $(titleLabel).parent().parent().find('.option1');
var option2 = $(titleLabel).parent().parent().find('.option2');
var selectOption = ($(titleLabel).parent().parent().find('select'));
var selectOptionID = ($(titleLabel).parent().parent().find('select').attr('id'));
$(selectOption).on('change', function () {
var selectedOption = $(selectOption).prop('value');
if (selectedOption == 1 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option2.addClass('hidden');
option1.removeClass('hidden');
}
if (selectedOption == 2 && checkbox.is(':checked')) {
InputInserireInput.addClass('hidden');
option1.removeClass('hidden');
option2.removeClass('hidden');
}
if (selectedOption == 0 && checkbox.is(':checked')) {
InputInserireInput.removeClass('hidden');
option1.addClass('hidden');
option2.addClass('hidden');
}
});
} else {
$('.inserirePrezzoDiv').addClass('hidden');
$(this).closest('div').parent().parent().find('.titoloPiega').css('color', '#a5a6a7');
$(this).closest('div').parent().parent().find('select').prop('value','0');
$(this).closest('div').parent().parent().find('.option1').addClass('hidden');
$(this).closest('div').parent().parent().find('.option2').addClass('hidden');
$('.bottoneCss6').css('margin-bottom', 0)
}
};
The first allert work but then all the if statement i thik doesn' match with the event declared before the function. Can anyone help me?
try by replacing :
$(":checkbox").on('change', function() {
$(this).myFunction()
})
you will pass the this (current checkbox) scope to myFunction

Why function(document) doesn't work in separate file?

I have an HTML file and this contain JavaScript code and works fine, but when I decided put the JS code in different file and call from the HTML file, doesn't work. Why?
The JS code is like this:
(function (document) {
var toggleDocumentationMenu = function () {
var navBtn = document.querySelector('.main-nav1');
var navList = document.querySelector('.main-nav2');
var navIsOpenedClass = 'nav-is-opened';
var navListIsOpened = false;
navBtn.addEventListener('click', function (event) {
event.preventDefault();
if (!navListIsOpened) {
addClass(navList, navIsOpenedClass);
navListIsOpened = true;
} else {
removeClass(navList, navIsOpenedClass);
navListIsOpened = false;
}
});
};
var toggleMainNav = function () {
var documentationItem = document.querySelector('.main-nav3');
var documentationLink = document.querySelector('.main-nav3 > .main-sub-nav');
var documentationIsOpenedClass = 'subnav-is-opened';
var documentationIsOpened = false;
if (documentationLink) {
documentationLink.addEventListener('click', function (event) {
event.preventDefault();
if (!documentationIsOpened) {
documentationIsOpened = true;
addClass(documentationItem, documentationIsOpenedClass);
} else {
documentationIsOpened = false;
removeClass(documentationItem, documentationIsOpenedClass);
}
});
}
};
var isTouch = function () {
return ('ontouchstart' in window) ||
window.DocumentTouch && document instanceof DocumentTouch;
};
var addClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(/\s+$/gi, '') + ' ' + className;
};
var removeClass = function (element, className) {
if (!element) {
return;
}
element.className = element.className.replace(className, '');
};
toggleDocumentationMenu();
toggleMainNav();
})(document);
I read it's possible that works if I put like this:
$(document).ready(function() {
// the javascript code here
});
But it still doesn't working.
Now I wonder, It's possible this code works fine in separate file?

Triggering the return key on event unexpectedly refreshes page and gives undefined error - JavaScript

When I click in field, type text, and press return on keyboard it triggers the initializeTable function that refreshes page and gives error form[0] undefined. However, when I use change event to change dropdown selection, it doesn't cause this unexpected behavior. So I'm not sure why pressing return key in text field is causing all this. Thanks for response.
<script>
(function($){
var listview = $('#listview');
var lists = (function(){
var criteria = {
dropFilter: {
insert: function(value){
if(value)
return {"filter" : value};
},
msg: "Filtering..."
},
searchFilter: {
insert: function(value){
if(value)
return {"search" : value}
},
msg: "Searching..."
}
}
return {
create: function(component){
var component = component.href.substring(component.href.lastIndexOf('#') + 1); //sites
return component;
},
setDefaults: function(component){
var parameter = {};
switch(component){
case "sites":
parameter = {
'url': 'sites',
'order': 'site_num',
'per_page': '20'
}
}
return parameter;
},
getCriteria: function(criterion){
return criteria[criterion];
},
addCriteria: function(criterion, method){
criteria[criterion] = method;
}
}
})();
var Form = function(form){
var fields = [];
$(form[0].elements).each(function(){
var field = $(this);
if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));
})
}
Form.prototype = {
initiate: function(){
for(field in this.fields){
this.fields[field].calculate();
}
},
isCalculable: function(){
for(field in this.fields){
if(!this.fields[field].alterData){
return false;
}
}
return true;
}
}
var Field = function(field){
this.field = field;
this.alterData = true;
this.component = {'url' : window.location.hash.substring(window.location.hash.indexOf('#') + 1)};
this.attach("change");
this.attach("keypress");
}
Field.prototype = {
attach: function(event){
var obj = this; //our Field object
if(event == "change"){
obj.field.bind("change", function(){
return obj.calculate();
})
}
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
return obj.calculate();
}
})
}
},
calculate: function(){
var obj = this,
field = obj.field,
component = obj.component,
msgClass = "msgClass",
msgList = $(document.createElement("ul")).addClass("msgClass"),
types = field.attr("alter-data").split(" "),
container = field.parent(),
messages = [];
field.next(".msgClass").remove();
for(var type in types){
var criterion = lists.getCriteria(types[type]);
if(field.val()){
var result = criterion.insert(field.val());
container.addClass("waitingMsg");
messages.push(criterion.msg);
obj.alterData = true;
initializeTable(component, result);
}
else {
return false;
obj.alterData = false;
}
}
if(messages.length){
for(msg in messages){
msgList.append("<li>" + messages[msg] + "</li");
}
}
else{
msgList.remove();
}
}
}
$('#dashboard a').click(function(){
var currentComponent = lists.create(this);
var defaults = lists.setDefaults(currentComponent);
initializeTable(defaults);
});
var initializeTable = function(defaults, custom){
var custom = custom || {};
var query_string = $.extend(defaults, custom);
var params = [];
$.each(query_string, function(key,value){
params += key + '=' + value + "&";
})
var url = params.substring(params.indexOf("url")+4,9);
params = params.substring(params.indexOf("&")+1).replace(params.substring(params.lastIndexOf("&")),"");
$.ajax({
type: 'GET',
url: '/' + url,
data: params,
dataType: 'html',
error: function(){},
beforeSend: function(){},
complete: function() {},
success: function(response) {
listview.html(response);
var form = $('form');
form.calculation();
}
})
}
$.extend($.fn, {
calculation: function(){
var formReady = new Form($(this));
if(!formReady.isCalculable){
return false;
}
}
})
})(jQuery)
</script>
Rather than going through whole script, the actual issue is with this:
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
return obj.calculate();
}
})
}
}
Finally, I got it to work this this:
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
return obj.calculate();
}
})
}
},
Hence, we first prevent default and then execute our custom function.

Categories

Resources