DateEdit set a date value on the client side - javascript

How to set date from one dateEdit to another.
I have two dateedit properties. When one dateEdit (date1) changes i need to set some value on another dateedit. I have created ondatechanged function which has some logics and then i need to set the value to date2 field. i have used js/jquery to set but the value does not bind properly after focusing or clicking the changed date2 Dateedit.
In my View
#Html.Hidden("dateTemp")
<label>R2Date</label>
#Html.DevExpress().DateEdit(
settings =>
{
settings.Name = "date1";
settings.Properties.NullText = "MM/dd/yyyy";
settings.Properties.EditFormat = EditFormat.Custom;
settings.Properties.EditFormatString = "MM/dd/yyyy";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(27);
settings.Properties.ClientSideEvents.DateChanged = "OnDateChanged";
}).Bind(Model.r2date).GetHtml()
<label>RDate</label>
#Html.DevExpress().DateEdit(
settings =>
{
settings.Name = "date2";
settings.Properties.NullText = "MM/dd/yyyy";
settings.Properties.EditFormat = EditFormat.Custom;
settings.Properties.EditFormatString = "MM/dd/yyyy";
settings.Width = System.Web.UI.WebControls.Unit.Percentage(27);
settings.Properties.ClientSideEvents.DateChanged = "ReportOnDateChanged";
}).Bind(Model.date1).GetHtml()
[JScript]
function OnDateChanged(s, e) {
var dateVal = s.GetText();
//my logic here
dateOnchange();
}
dateOnchange(){
//my logic here just need to call reportondatechange()
ReportOnDateChanged();
}
function ReportOnDateChanged(s,e )
{
dateVal1 = $("#dateTemp").val(); //dateval1 has some values here
s.SetDate(dateVal1);//not working how to set the value here
}

https://documentation.devexpress.com/#AspNet/DevExpressWebScriptsASPxClientControl_GetControlCollectiontopic
This should do it
var editor = ASPxClientControl.GetControlCollection().GetByName("date2");
if (editor) {
editor.SetValue(dateVal1);
}
$("#date2").val(dateVal1);

Related

How to set expiry date on pop-up in javascript

I have a modal which appears once per user , and I am using local storage to achieve this. However, I am now trying to make it so that after a certain date ( 1/03/2022) to not appear at all. Here is my logic at the moment:
$(document).ready(function () {
var key = 'hadModal',
hadModal = localStorage.getItem(key);
if (!hadModal) {
$('#PIAModal').modal('show');
}
$(".btn").click(function () {
localStorage.setItem(key, true);
$("#PIAModal").modal('hide');
});
$(".modal").click(function () {
localStorage.setItem(key, true);
$("#PIAModal").modal('hide');
});
You can make a function to check if it's the due date and pass it to the conditional
function isBeforeDate() {
let today = new Date();
const endDate = new Date("2022-03-01");
if (today < endDate) {
return true
} else {
return false
}
}
if (!hadModal && isBeforeDate()) {
$('#PIAModal').modal('show');
}
You can create Date objects in Javascript and compare them.
var now = new Date();
var end = new Date("2022-03-01");
if (now < end) {
$('#PIAModal').modal('show');
}

JavaScript - Issues recovering a map in an object after being saved in localStorage

I've been dealing with this for some time. I've a list of sections in which the user checks some checkboxes and that is sent to the server via AJAX. However, since the user can return to previous sections, I'm using some objects of mine to store some things the user has done (if he/she already finished working in that section, which checkboxes checked, etc). I'm doing this to not overload the database and only send new requests to store information if the user effectively changes a previous checkbox, not if he just starts clicking "Save" randomly. I'm using objects to see the sections of the page, and storing the previous state of the checkboxes in a Map. Here's my "supervisor":
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
var children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children().length;
for (var i = 0; i < children; i++) {
if (i % 2 == 0) {
var checkbox = $("#ContentPlaceHolder1_checkboxes_div_" + id).children()[i];
var idCheck = checkbox.id.split("_")[2];
this.selections.set(idCheck, false);
}
}
console.log("Length " + this.selections.size);
this.change = false;
}
The console.log gives me the expected output, so I assume my Map is created and initialized correctly. Since the session of the user can expire before he finishes his work, or he can close his browser by accident, I'm storing this object using local storage, so I can change the page accordingly to what he has done should anything happen. Here are my functions:
function setObj(id, supervisor) {
localStorage.setItem(id, JSON.stringify(supervisor));
}
function getObj(key) {
var supervisor = JSON.parse(localStorage.getItem(key));
return supervisor;
}
So, I'm trying to add to the record whenever an user clicks in a checkbox. And this is where the problem happens. Here's the function:
function checkboxClicked(idCbx) {
var idSection = $("#ContentPlaceHolder1_hdnActualField").val();
var supervisor = getObj(idSection);
console.log(typeof (supervisor)); //Returns object, everythings fine
console.log(typeof (supervisor.change)); //Returns boolean
supervisor.change = true;
var idCheck = idCbx.split("_")[2]; //I just want a part of the name
console.log(typeof(supervisor.selections)); //Prints object
console.log("Length " + supervisor.selections.size); //Undefined!
supervisor.selections.set(idCheck, true); //Error! Note: The true is just for testing purposes
setObj(idSection, supervisor);
}
What am I doing wrong? Thanks!
Please look at this example, I removed the jquery id discovery for clarity. You'll need to adapt this to meet your needs but it should get you mostly there.
const mapToJSON = (map) => [...map];
const mapFromJSON = (json) => new Map(json);
function Supervisor(id) {
this.id = id;
this.verif = null;
this.selections = new Map();
this.change = false;
this.selections.set('blah', 'hello');
}
Supervisor.from = function (data) {
const id = data.id;
const supervisor = new Supervisor(id);
supervisor.verif = data.verif;
supervisor.selections = new Map(data.selections);
return supervisor;
};
Supervisor.prototype.toJSON = function() {
return {
id: this.id,
verif: this.verif,
selections: mapToJSON(this.selections)
}
}
const expected = new Supervisor(1);
console.log(expected);
const json = JSON.stringify(expected);
const actual = Supervisor.from(JSON.parse(json));
console.log(actual);
If you cant use the spread operation in 'mapToJSON' you could loop and push.
const mapToJSON = (map) => {
const result = [];
for (let entry of map.entries()) {
result.push(entry);
}
return result;
}
Really the only thing id change is have the constructor do less, just accept values, assign with minimal fiddling, and have a factory query the dom and populate the constructor with values. Maybe something like fromDOM() or something. This will make Supervisor more flexible and easier to test.
function Supervisor(options) {
this.id = options.id;
this.verif = null;
this.selections = options.selections || new Map();
this.change = false;
}
Supervisor.fromDOM = function(id) {
const selections = new Map();
const children = $("#ContentPlaceHolder1_checkboxes_div_" + id).children();
for (var i = 0; i < children.length; i++) {
if (i % 2 == 0) {
var checkbox = children[i];
var idCheck = checkbox.id.split("_")[2];
selections.set(idCheck, false);
}
}
return new Supervisor({ id: id, selections: selections });
};
console.log(Supervisor.fromDOM(2));
You can keep going and have another method that tries to parse a Supervisor from localStorageand default to the dom based factory if the localStorage one returns null.

How do I check for a JSON string value in a jS if statement?

I'm calling user data from Memberstack which allows data to be stored as metadata in JSON. I have the following code:
// Set Variables //
var initiated = "Y" <--- demonstration purposes only
var startDate = new Date();
var currentDate = new Date();
// End set variqables. //
// Check initiated state. //
MemberStack.onReady.then(async function(member) {
var metadata = await member.getMetaData()
if (metadata = initiated.includes("Y")) {
runTimer();
} else {
var sDobj = {
startDate: startDate,
}
var initY = {
initiated: "Y"
}
var sDobjjson = JSON.stringify(sDobj);
var initYjson = JSON.stringify(initY);
member.updateMetaData(sDobj, initY)
}
})
// End check initiated state. //
Most of this is working except for the initial if statement (if (metadata = initiated.includes("Y"))) which is currently linked to the variable var initiated = "Y". What I need to do is search the data I have returned under the metadata string response instead of the predefined initiated variable value.
Here is console which correctly returns metadata = {"initiated":"N"} from Memberstack:
Can anybody help me to get my if statement on line 28 if (metadata = initiated.includes("Y")) to read the string value on line 26 metadata = {"initiated":"N"} instead of the predefined variable var initiated = "Y"?
Change this to
if (metadata = initiated.includes("Y")) {
runTimer();
}
This
if (metadata.initiated === "Y") {
runTimer();
}
The issue is that you are assigning the result of the validation to metadata. Also the initiated variable will not be accessible at that line as it is not defined yet

How to use localStorage to save variable with random value

I'm trying to use localStorage to save a variable with value generated randomly from an array in a JavaScript file, and pass it to another HTML file. However, the value in Javascript file (Random_Msg) and the value in HTML file (Random_Msg1) are not the same, means it's not saved, instead it generated randomly another value.
These are the code to generate variable and save in localStorage:
function CreateRandomMsg(){
var RandomMsg = Msgs_Arr[Math.floor(Math.random()* Msgs_Arr.length)];
return RandomMsg;
}
var Random_Msg = CreateRandomMsg();
function alertMsg(){
alert(Random_Msg);
}
window.localStorage.setItem("Random_Msg1",Random_Msg);
In my HTML file, I just retrieved the variable first:
var Random_Msg1 = window.localStorage.getItem("Random_Msg1");
And use it in if statement:
if (Random_Msg1 == Msgs_Arr[0] || Random_Msg1 == Msgs_Arr[1]){
value = facesDet.photos[0].tags[0].attributes.glasses.value;
confidence = facesDet.photos[0].tags[0].attributes.glasses.confidence;
} else if (Random_Msg1 == Msgs_Arr[2] || Random_Msg1 == Msgs_Arr[3]) {
value = facesDet.photos[0].tags[0].attributes.smiling.value;
confidence = facesDet.photos[0].tags[0].attributes.smiling.confidence;
};
You can check on pageload if value for necessary key exists in localStorage. If value is missing, then compute and save new value. You can also have an extra event on which you can override value of this key, but this will be a user action.
Note: Stack Overflow does not give access to localStorage and any testing should be done on JSFiddle.
Sample
JSFiddle
function computeRandomValue() {
var data = ["test", "test1", "test2", "test3", "test4"];
var index = Math.floor(Math.random() * 10) % data.length;
return data[index];
}
function setToLocalStorage(newVal) {
var lsKey = "_lsTest";
localStorage.setItem(lsKey, newVal);
}
function getFromLocalStorage() {
var lsKey = "_lsTest";
return localStorage.getItem(lsKey);
}
function initializePage() {
var _val = getFromLocalStorage();
if (!(_val && _val.trim().length > 0)) {
_val = computeAndSaveNewValue();
}
printValue(_val, "lblResult");
}
function computeAndSaveNewValue() {
var newVal = computeRandomValue();
setToLocalStorage(newVal);
printValue(newVal);
return newVal;
}
function printValue(value) {
var id = "lblResult";
document.getElementById(id).innerHTML = value;
}
(function() {
window.onload = initializePage;
})()
<p id="lblResult"></p>
<button onclick="computeAndSaveNewValue()">Save new Value</button>

Reference issue with Javascript

I have an array of objects cached on client side using JS array.
var scannerDictionary = new Array(); //Holds all scanners unmodified
var modifiedScannerDictionary = new Array(); //Holds all scanners with modified values
The properties of each object is set/changed using GUI and updated in the object. Each object contains list of InputParameters (array of Parameter class containing Name, Value and other members).
Please have a look on GUI.
Below is the code i used to render the controls -
function renderControls(scannerId) {
var currentScanner = modifiedScannerDictionary[scannerId];
//Render Input Parameters
$("#tblInputCriteria").find('tr:gt(5)').remove();
for(var i=0;i<currentScanner.InputParameters.length;i++) {
var propType = currentScanner.InputParameters[i].DataType;
var inParName = currentScanner.InputParameters[i].Name;
switch(propType) {
case 0: //Number
var eRow1 = $("#tblInputCriteria").find('#emptyNumRow').clone();
$(eRow1).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow1).appendTo($('#tblInputCriteria'));
var prop1 = $(eRow1).find('#InNumPropName');
$(prop1).attr('id', 'InNumPropName_'+currentScanner.InputParameters[i].Name);
var propName1 = currentScanner.InputParameters[i].Name;
$(prop1).html(propName1);
var propVal1 = $(eRow1).find('#InNumPropValue');
$(propVal1).attr('id', 'InNumPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal1).val(currentScanner.InputParameters[i].Value);
$(propVal1).blur(function () {
if(!ValidateNumber(this, propName1)) {
alert('Value should be numeric in ' + propName1);
setTimeout(function() {$(propVal1).focus();}, 100);
}else {
UpdateData(currentScanner.Id, propName1, $(propVal1).val());
}
});
break;
case 1: //String
var eRow2 = $("#tblInputCriteria").find('#emptyStrRow').clone();
$(eRow2).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow2).appendTo($('#tblInputCriteria'));
var prop2 = $(eRow2).find('#InStrPropName');
$(prop2).attr('id', 'InStrPropName_'+currentScanner.InputParameters[i].Name);
var propName2 = currentScanner.InputParameters[i].Name;
$(prop2).html(propName2);
var propVal2 = $(eRow2).find('#InStrPropValue');
$(propVal2).attr('id', 'InStrPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal2).val(currentScanner.InputParameters[i].Value);
$(propVal2).blur(function () {
UpdateData(currentScanner.Id, propName2, $(propVal2).val());
});
break;
case 2: //Boolean
var eRow3 = $("#tblInputCriteria").find('#emptyBoolRow').clone();
$(eRow3).removeClass('hidden').attr('id', 'Row_'+currentScanner.InputParameters[i].Name);
$(eRow3).appendTo($('#tblInputCriteria'));
var prop3 = $(eRow3).find('#InBoolPropName');
$(prop3).attr('id', 'InBoolPropName_'+currentScanner.InputParameters[i].Name);
var propName3 = currentScanner.InputParameters[i].Name;
$(prop3).html(propName3);
var propVal3 = $(eRow3).find('#InBoolPropValue');
$(propVal3).attr('id', 'InBoolPropValue_'+currentScanner.InputParameters[i].Name);
$(propVal3).val(currentScanner.InputParameters[i].Value);
$(propVal3).blur(function () {
UpdateData(currentScanner.Id, propName3, $(propVal3).val());
});
break;
}
}
}
PROBLEM:
The problem here is of the variables inside switch working as reference variable. So the UpdateData() function gets the last Name for similar type properties. i.e. if fields are of Number type then only the last property is updated by UpdateData() method.
Can anybody help me out solve this issue. Thanks for sharing your time and wisdom.
Try something like the following. Its a tad overkill, but will bind the values of the variables to the closures.
var fnOnBlur = (function(thePropName, thePropVal) {
return function () {
if(!ValidateNumber(this, thePropName)) {
alert('Value should be numeric in ' + thePropName);
setTimeout(function() {$(thePropVal).focus();}, 100);
}else {
UpdateData(currentScanner.Id, thePropName, $(thePropVal).val());
}
};
})(propName1, propVal1);
$(propVal1).blur( fnOnBlur );
The link that Felik King supplied has much more detailed discussion.

Categories

Resources