How to delete and object from and array - javascript

Thanks for your help in advance. I have been trying for two days how to delete an object which is stored in an array and I dont get it. Just reading a lot on forums and trying, but nothing works.
<head>
<style>
</style>
<script type="text/javascript">
//Global Array to saved more than one object without having to declare all of them
var car = {};
var i;
var numRecords2 = 0;
var doors;
var outOfDateInsurance;
var contRecords = -1;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var istart = contRecords + 1;
var iend = numRecords2 + numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (i = istart; i < iend; i++)
{
contRecords++;
var record = contRecords;
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the object car in the Class Cars
car[i] = new Cars(record, brand, color, doors, insurance, outOfDateInsurance);
}
numRecords2 = numRecords2 + numRecords;
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (i = 0; i < numRecords2; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
car[0] = null;
car.splice(0);
for (i = 0; i <= contRecords; i++)
{
alert(car[i]);
}
//if (contRecords >=0)
//{
// var numRecordToDelete = prompt("Introduce the record's number you want to delete");
// numRecordToDelete = parseInt(numRecordToDelete);
// if (isNaN(numRecordToDelete) === false)
// {
// //var i = numRecordToDelete;
// //
// // alert('Record: ' + i);
// //if(car[i].record === 'Record: ' + i)
// //{
// // alert('Record: ' + i);
// // car.splice(i,1);
// // return false;
// //}
// car.shift();
// document.getElementById("container").innerHTML = car;
// }
// else
// {
// alert("The character you have introduce is not a number");
// deleteCar();
// }
//}
//else
//{
// alert("There are no any record to delete");
// return;
//}
}
</script>
</head>
<body>
<h1 style="text-align: center;">WELLCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>
</body>
So the thing is, I am adding objects to the array like a BBDD and i dont know how to do it to delete one object from the array and re-organize the other objects in the array's positions like, if I delete the element's array number 2, then, the number 3 will be the second one and the fodth one would be the third, etc...
Thanks a lot, any doubt, please, let me know. I really appreciate your help.

//Global Array to saved more than one object without having to declare all of them
var car = [],
doors,
outOfDateInsurance;
// Class Cars
function Cars(record, brand, color, doors, insurance, outOfDateInsurance)
{
this.record = record;
this.brand = brand;
this.color = color;
this.doors = doors;
this.insurance = insurance;
this.outOfDateInsurance = outOfDateInsurance;
}
//To validate number of the doors. It has to be 3 or 5
function validateDoors()
{
doors = prompt("Number of doors");
doors = parseInt(doors);
if (isNaN(doors) === false && (doors == 3 || doors == 5))
{
return;
}
else
{
alert("Wrong character. Please, set 3 or 5");
validateDoors();
}
}
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
if ((outOfDateInsurance.match(RegExPattern)) && (outOfDateInsurance!=''))
{
return true;
}
else
{
return false;
}
}
//To check if the date is in the calendar
function realDate(outOfDateInsurance)
{
var fechaf = outOfDateInsurance.split("/");
var d = fechaf[0];
var m = fechaf[1];
var y = fechaf[2];
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
}
//To validate the date is over today
function validateAboveDate(outOfDateInsurance)
{
var datef = outOfDateInsurance.split("/");
var d = datef[0];
var m = datef[1];
var y = datef[2];
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10)
{
dd='0'+dd
}
if(mm<10)
{
mm='0'+mm
}
var today = dd+'/'+mm+'/'+yyyy;
var todayf = today.split("/");
var dt = todayf[0];
var mt = todayf[1];
var yt = todayf[2];
if ((d > dt) && (m >= mt) && (y >= yt))
{
return true;
}
else
{
if ((d = dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
if ((d < dt) && (m > mt) && (y >= yt))
{
return true;
}
else
{
return false;
}
}
}
}
//To validate the date's is right
function checkingDate()
{
outOfDateInsurance = prompt("Insurance's End date (dd/mm/yyyy)");
if(validateFormatDate(outOfDateInsurance))
{
if(realDate(outOfDateInsurance))
{
if (validateAboveDate(outOfDateInsurance))
{
alert("Record has been introduced into the system");
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
else
{
alert("You have introduced an incorrect Insurance's End date");
checkingDate();
}
}
//To create objects
function addCar()
{
var numRecords = prompt("How many records do you want to introduce to the system?");
numRecords = parseInt(numRecords);
if (isNaN(numRecords) === false)
{
var iend = numRecords;
//problema aƱadiendo cars porque reemplaza si no lo hago todo de una vez
for (var i = 0; i < iend; i++)
{
var brand = prompt("Car's Brand");
var color = prompt("Car's Color");
validateDoors();
var insurance = confirm("Does have the car insurance? Press OK for YES and CANCEL for NO");
if (insurance === true)
{
insurance = "Yes";
checkingDate();
}
else
{
insurance = "No";
alert("Record has been introduced into the system");
}
//CONSTRUCTOR We are creating the ARRAY car in the Class Cars
car.push(new Cars(car.length + 1, brand, color, doors, insurance, outOfDateInsurance));
}
}
else
{
alert("Please, introduce the number of the records you want to introduce");
addCar();
}
displayCar();
}
//To display the objects created
function displayCar()
{
document.getElementById("container").innerHTML = "";
for (var i = 0; i < car.length; i++)
{
//we are creating an element <p>
var parag = document.createElement('p');
parag.id = "paragraph" + i;
//we are creating an element <br>
var br = document.createElement('br');
//we are creating a text node
var textRecord = document.createTextNode("Record: " + car[i].record);
var textBrand = document.createTextNode("Brand: " + car[i].brand);
var textColor = document.createTextNode("Color: " + car[i].color);
var textDoors = document.createTextNode("Number of doors: " + car[i].doors);
var textInsurance = document.createTextNode("Insurance: " + car[i].insurance);
if (car[i].insurance === "Yes")
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: " + car[i].outOfDateInsurance);
}
else
{
var textOutOfDateInsurance = document.createTextNode("Date Insurance: ");
}
//we are adding the text nodes created to the <p>
parag.appendChild(textRecord);
//We are creating a clone from a node to have multiple break lines
parag.appendChild(br.cloneNode());
parag.appendChild(textBrand);
parag.appendChild(br.cloneNode());
parag.appendChild(textColor);
parag.appendChild(br.cloneNode());
parag.appendChild(textDoors);
parag.appendChild(br.cloneNode());
parag.appendChild(textInsurance);
parag.appendChild(br.cloneNode());
parag.appendChild(textOutOfDateInsurance);
//we are adding the whole <p> with the text nodes into the div created in the html
document.getElementById("container").appendChild(parag);
}
}
function deleteCar()
{
if (car.length >0)
{
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
numRecordToDelete = parseInt(numRecordToDelete);
if (isNaN(numRecordToDelete) === false)
{
alert('Record: ' + numRecordToDelete);
if(numRecordToDelete >= car.length)
{
alert('Record: ' + numRecordToDelete);
car.splice(numRecordToDelete - 1,1);
displayCar();
return false;
}
else {
alert("Record not exist");
deleteCar();
}
}
else
{
alert("The character you have introduce is not a number");
deleteCar();
}
}
else
{
alert("There are no any record to delete");
return;
}
}
<h1 style="text-align: center;">WELCOME TO THE AMAZING SOFTWARE TO ADD CARS TO YOUR SYSTEM</h1>
<br><br>
<!-- Button to create the object car -->
<input type="button" value="Add Car" onclick="addCar()">
<!-- Button to display the objects created -->
<input type="button" value="See Cars" onclick="displayCar()">
<input type="button" value="Delete Cars" onclick="deleteCar()">
<BR>
<hr>
<BR>
<!-- Div which information's objects is going to be displayed -->
<div id="container"></div>

You can use Array.splice() to delete entries from an array.
Link
car.splice(0,1);

I should you work with an array of objects. Actually you work with an object how array where re many objects. With this is more easy foreach actual cars to add, see and delete.
car = [];
when add:
car.push(new Cars(record, brand, color, doors, insurance, outOfDateInsurance));
Other than that, I suggest you when you add or delete car, refresh data for the client can see changes and refreshing records number for deletes.
When your splice a element of array, the other elements after will move -1. For this reason must call displayCar() at the end.
var numRecordToDelete = prompt("Introduce the record's number you want to delete");
car.splice(numRecordToDelete,1);

I believe I understand what you are looking for and the example provided should address that, if not let me know.
<script>
var collectionOfObjects = [];
collectionOfObjects.push({name: "anObject1"});
collectionOfObjects.push({name: "anObject2"});
collectionOfObjects.push({name: "anObject3"});
collectionOfObjects.push({name: "anObject4"});
console.log("collectionOfObjects initial state");
console.log(collectionOfObjects);
console.log("deleteing 2nd member - this will delete the object even if other things have reference to it and not just remove it from the collection");
console.log("deleteing 2nd member - it will croupt the length of the array but we can fix that");
delete collectionOfObjects[2];
collectionOfObjects = collectionOfObjects.sort();
collectionOfObjects.length = collectionOfObjects.length - 1
console.log("collectionOfObjects after delete");
</script>
On a side note I just noticed you could do this also:
//To validate date's format
function validateFormatDate(outOfDateInsurance)
{
var RegExPattern = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;
return outOfDateInsurance.match(RegExPattern) && (outOfDateInsurance!='')
}

Related

mutliple set timeouts running at once

so, i have a for loop that I want to run multiple set timeouts at once so it can continually check if it is a certain time for multiple times. i can't just check for all multiple times all at once, the check needs to repeat after different amounts of time. it only continues to repeat the last iteration of the loop, the last dict in lat.
my approach simplified a bit:
lat = list of dictionaries with some values that differentiate them + times
for(i = 0; i< lat.length; i++){
if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,30000)
}
else{
console.log("yay the time is right!")
}
}
else if(lat[i][differentiate value]) = {
function checktime(){
if(currenttime != lat[i]){
setTimeout(checktime,50000)
}
else{
console.log("yay the time is right!")
}
}
}
How would I go about making this (its for a notification app)
original code:
(each value in later looks like [[75,null,[7,28,2021]], null,[[9,52,"p"]],"e&r"] with the amount of notifications, a preset date, the date for these reminders to be on, by time, which would be the first if, and the array of at times. for testing I had 2 laters with 2 different at times):
chrome.storage.sync.get('later', function(data){
if (data.later !== null){
var lat = data.later;
for(i = 0; i< lat.length; i++){
var currentDict = lat[i];
if(currentDict['notis'][1] !== null){
console.log("cheese")
var by = currentDict['notis'][1];
console.log(by)
const d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var h = by[0];
var m = by[1];
var ampm = by[2];
if(ampm == "p"){
h = h + 12;
}
var byMS = h*3600000 + m*60000;
var currentMS = hr*3600000 + min*60000 + sec*1000;
//check if right date then check if time is lesss than
function checkdate(){
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
var amt = 0;
function checktime(){
if(byMS >= currentMS){
//noti and delete
var int = setInterval(function(){
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
amt++
console.log(amt)
const dddd = new Date();
console.log(dddd.getMinutes() + " / " + dddd.getSeconds())
if(amt >= currentDict['notis'][0][0]){
clearInterval(int)
console.log("done")
//ju finish taht
console.log(lat)
lat.splice(lat.indexOf(currentDict),1)
console.log(lat)
chrome.storage.sync.set({'later': lat})
}
}, (byMS-currentMS)/currentDict['notis'][0][0])
}
else{
setTimeout(checktime,30000)
}
}
checktime();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
else if(currentDict['notis'][2] !== null){
console.log("cheese")
var at = currentDict['notis'][2];
console.log(at)
var arrayat = [];
for(j = 0; j<= at.length-1; j++){
var atcycle = at[j];
console.log(atcycle)
const ddd = new Date();
var hr = ddd.getHours();
var min = ddd.getMinutes();
var da = currentDict['notis'][0][2][1];
var mo = currentDict['notis'][0][2][0];
var ye = currentDict['notis'][0][2][2]
var hrat = atcycle[0];
var minat = atcycle[1];
var ampm = atcycle[2];
if(ampm == "p"){
hrat = hrat + 12;
}
console.log(hrat + "/" + minat + "/" + ampm)
if(hr <= hrat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)
}
else if(hr == hrat){
if(min<minat){
var temparray = [];
temparray.push(hrat)
temparray.push(minat)
arrayat.push(temparray);
console.log(arrayat)}
}
}
console.log(arrayat.length)
function checkdate(){
console.log(arrayat.length)
console.log("date")
const d = new Date();
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if(da == day && mo == month && ye == year){
function check(){
console.log(arrayat.length)
console.log("check")
for(l=0; l<arrayat.length; l++){
console.log(arrayat.length)
const dd = new Date();
var hr = dd.getHours();
var min = dd.getMinutes();
console.log(arrayat[l][1])
console.log(min)
if(arrayat[l][0] == hr && arrayat[l][1] == min ){ //at one of the times
console.log(arrayat)
arrayat.splice(l,1)
console.log(arrayat)
if(arrayat.length == 0){
lat.splice(lat.indexOf(currentDict),1)
chrome.storage.sync.set({'later': lat})
console.log(lat)
}
chrome.notifications.create({
title: currentDict['name'],
message: "do da " + currentDict['name'],
iconUrl: "logo.png",
type: "basic"
})
//add noti with name and delete it
console.log(arrayat)
check();
}
}
console.log(arrayat.length)
if(arrayat.length !== 0){
console.log("and repeat")
setTimeout(check,15000);//SETINTERVAL INSTEAD? ANDCLEAR
}
}
check();
}
else{
setTimeout(checkdate,66400000)
}
}
checkdate();
}
}
}
})
}
This is the wrong approach. You know the times, so you know how far off they are in time. You don't need to check over and over again if the time has arrived. Instead work out how many milliseconds until the time in question, then set a timeout for that time.
You basically need to pass different functions to each setTimeout():
function checktime1(){
if(currenttime != lat[i]){
setTimeout(checktime1,30000)
}
else{
console.log("yay the time is right!")
}
}
function checktime2(){
if(currenttime != lat[i]){
setTimeout(checktime2,50000)
}
else{
console.log("yay the time is right!")
}
}
However, this is obviously not scalable. If you have lots of timeouts you will be writing lots of duplicate functions. Worse, if you have a dynamic number of timeouts this won't solve your problem.
Fortunately, javascript lets us declare functions inside another function:
function checktime(timeout){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log("yay the time is right!")
}
}
loop();
}
This allows you to dynamically create functions as needed:
checktime(30000);
checktime(50000);
If you need to pass arguments to each timeouts (eg. if you need to display custom alerts) you can just pass it to your outer function and it will be captured in a closure:
function checktime(timeout, message){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout)
}
else{
console.log(message)
}
}
loop();
}
Then you can do:
checktime(30000, "Yay, the time is right for timer 1");
checktime(50000, "Yay, the time is right for timer 2");
Similarly, if you need to execute custom logic for each timer you can also pass it as an argument (callback):
function checktime(timeout, callback){
function loop () {
if(currenttime != lat[i]){
setTimeout(loop,timeout);
}
else{
console.log("yay the time is right!");
callback(); // <----------------- execute custom logic
}
}
loop();
}
Which you can use like:
checktime(30000, () -> console.log("TIMER 1"));
checktime(50000, () -> alert("TIMER 2"));

JQUERY, highlight a column if contains numbers in sequence

I'm struggling in how to make this simple code work: i only want to check the values of every column and see if they are sequential (like 0 to 7 for example), and if so, highlight that column (class = "snaked" ).
So i marked every cell which belongs to the first row (class = "vstarter") and i tried out this :
function is_colsnake() {
ognicella.filter(".vstarter").each(
function() {
var cella = $(this);
var pos = cella.index();
var colonna = ognicella.filter(":nth-child(" + (pos + 1) + ")")
var col = [];
var issnake = false;
colonna.each(
function() {
col.push(parseInt($(this).text()));
});
col.each(
function() {
var start = parseInt($(this).text()) ;
var next = parseInt($(this).next().text()) ;
var prev = parseInt($(this).prev().text()) ;
var ix = $(this).index() ;
if (ix == 0) {
if (next == start + 1) {
issnake = true;
} else {
issnake = false;
}
} else if (start != prev + 1) {
issnake = false;
}
});
if (issnake) {
colonna.each(function() {
$(this).addClass("snaked");
})
} else {
colonna.each(function() {
$(this).removeClass("snaked");
})
}
})
};
However it isn't working. Would you please help?

Getting the JavaScript inside the codebehind to return true or false?

I'm having an issue with calling a JavaScript function while in the codebehind method:
This code populates the textboxes with the cookieValues data. The JavaScript CalculateDOBAge gets called and does an existing DOB calculation and determines if the Age being returned is the same age as the DOB being returned.
However, if it determines that the DOB calculates a different Age then what is being returned I want to clear out the txtDOB and txtMonths textboxes. This is the part that isn't working.
ASP.Net Code Behind:
private void LoadSheetValues()
{
txtDOB.Text = cookieValues["DOB"];
txtAge.Text = cookieValues["Age"];
txtMonths.Text = cookieValues["Months"];
ClientScript.RegisterStartupScript(GetType(), "CalculateDOBAge", "calcDOBAge()", true);
}
JavaScript snippet:
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
The javascript code is called from the ClientScript.RegisterStartupScript call and I can step through the values being blanked out. However, I think I dealing with a page lifecycle issue as when I check the screen after completion, the values remain in the textboxes.
I need the RegisterStartupScript (vs RegisterClientScriptBlock) as the CalculateDOBAge function needs the elements to be available and populated (so I can do the DOB calculation).
Is there a way to set this up using the RegisterStartupScript to return a True/False and then I can continue in the codebehind to clear out the textbox text?
Unfortunately this is an ancient application and jQuery or any modern frameworks are not available.
Full JavaScript:
function DOBAgeMonthCheck(birthDate, dateFormat) {
try {
if (dateFormat == 'MMDD') {
var bmo = birthDate.substr(0, 2);
var bday = birthDate.substr(3, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'DDMM') {
var bmo = birthDate.substr(3, 2);
var bday = birthDate.substr(0, 2);
var byr = birthDate.substr(6, 4);
} else if (dateFormat == 'YMD') {
var byr = birthDate.substr(0, 4);
var bmo = birthDate.substr(5, 2);
var bday = birthDate.substr(8, 2);
}
//replaces *ALL* "_" with ""
byr = byr.replace(/_/g, "");
bmo = bmo.replace(/_/g, "");
bday = bday.replace(/_/g, "");
var yrDiff;
var displayMonth;
var displayYear;
var now = new Date();
tday = now.getDate();
tmo = now.getMonth() + 1; //January is 0!
tyr = now.getFullYear();
//set four digit year
var tmpYr = tyr.toString();
byr = removeLeadingZero(byr);
var tmpLength = byr.length;
if (tmpLength < 4) {
if (byr > tmpYr.substr(2, 2))
byr = "1900".substr(0, 4 - tmpLength) + byr;
else
byr = "2000".substr(0, 4 - tmpLength) + byr;
}
if ((tmo > bmo) || (tmo == bmo & tday >= bday))
yrDiff = parseInt(byr)
else
yrDiff = parseInt(byr) + 1
if (tyr - yrDiff < 0)
displayYear = 0;
else
displayYear = (tyr - yrDiff);
if (tmo >= bmo)
displayMonth = tmo - parseInt(bmo);
else
displayMonth = 12 - (parseInt(bmo) - tmo);
var age;
var months;
try { age = document.getElementById("txtAge").value; } catch (err) { }
try { months = document.getElementById("txtMonths").value; } catch (err) { }
if ((displayYear == age) && (displayMonth == months)) {
//The SAME
} else {
//Different
document.getElementById("txtDOB").value = '';
document.getElementById("txtMonths").value = '';
}
}
catch (err) { }
}
I'm getting to the //Different section and watching the values being cleared.

Time overlap issue javascript

I am working in add task module in my project.i want to check every time task add check if existing tasks overlap or not. i am almost did but,one problem occur on time overlap condition not allow add task, example if user add tasks below times like below:
09:00 AM - 10:00 AM
10:30 AM - 11:00 AM
if i add tasks to between 10:00 AM to 10:30 AM not allowed in my condition on below:
function disabletime(start_time, end_time) {
var start_date = new Date(new Date(start_time).getTime());
var end_date = new Date(new Date(end_time).getTime());
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = Date.parse("1-1-2000 " + tasks_array[i].start_time);
var prev_e_date = Date.parse("1-1-2000 " + tasks_array[i].end_time);
var prev_start_date = new Date(new Date(prev_s_date).getTime());
var prev_end_date = new Date(new Date(prev_e_date).getTime());
if (i == 0) {
min_date = prev_start_date.getTime();
max_date = prev_end_date.getTime();
} else {
if (prev_end_date.getTime() > max_date) {
max_date = prev_end_date.getTime();
}
if (prev_start_date.getTime() < min_date) {
min_date = prev_start_date.getTime();
}
}
}
if ((start_date.getTime() == min_date) && (end_date.getTime() == max_date)) {
alert("Check the start and end time for this task!");
return false;
} else if ((start_date.getTime() < min_date) && (end_date.getTime() <= min_date) || (start_date.getTime() >= max_date) && (end_date.getTime() > max_date)) {
} else {
alert("Check the start and end time for this task!");
return false;
}
}
start_date = new Date(start_date.getTime() + 30 * 60000);
while (start_date < end_date) {
disable_times.push([start_date.getHours(), start_date.getMinutes()]);
start_date = new Date(start_date.getTime() + 30 * 60000);
}
return true;
}
here is my code flow, i add all tasks into json array in javascript. every time add new task check existing tasks on json array objects(inside if tasks exist) time overlap or not.
Here is a fiddle
I think it's a 'refactor if you want to debug' case.
Just breaking you problems into well isolated, small, simple problems will lead you to a solution faster than any deep debug cession.
You should break down the complexity of your code by using objects,
so you'll have a clear view on who does what, and you can test
easily each part.
I'm not sure the code below complies with all your needs, but it
should be much easier to use : i defined 2 objects : a task,
and a set of task.
For each i defined pretty simple methods, easy to read and debug.
I did not test the result, but you'll get the idea on how to do what
you want from here.
http://jsfiddle.net/gamealchemist/b68Qa/2/
// ------------------------------
// Task
function Task(startDate, endDate) {
this.start = startDate;
this.end = endDate;
}
// returns wether the time range overlaps with this task
Task.prototype.overlap = function (start, end) {
return (this.start <= end && this.end >= start);
}
// returns a string describing why the task is wrong, or null if ok
function checkTask(start, end) {
if (start > end) return "End time should exceed the start time";
if (start == end) return "End time should not same as the start time";
return null;
}
and now a set of tasks :
// ------------------------------
// Task Set
function TaskSet() {
this.tasks = [];
this.minDate = 0;
this.maxDate = 0;
}
// returns a string describing why the task cannot be added, or null if ok
TaskSet.prototype.check = function (start, end) {
var tasks = this.tasks;
// 1. Check date is valid
var dateCheck = checkTask(start, end);
if (dateCheck) return dateCheck;
// 2. overlap check
for (var i = 0; i < tasks.length; i++) {
var thisTask = tasks[i];
if (thisTask.overlap(start, end)) {
return 'time overlaps with another task';
}
}
return null;
}
// add the task.
TaskSet.prototype.add = function (start, end) {
var tasks = this.tasks;
if (task.length) {
this.minDate = start;
this.maxDate = end;
}
if (start < minDate) minDate = start;
if (end > maxDate) maxDate = end;
// you might want to check before inserting.
tasks.push(new Task(start, end));
}
// displays the current task inside the tasks div.
TaskSet.prototype.show = function () {
var tasks_array = this.tasks;
$("#tasks").html('');
$.each(tasks_array, function (index, item) {
var newRowContent = "<div>" + item.start_time + "-" + item.end_time + "</div>";
$("#tasks").append(newRowContent);
});
}
Let's use those objects :
// ---------------------------
var myTasks = new TaskSet();
$("#addtask").click(handle_AddTask_Clicked);
function handle_AddTask_Clicked(e) {
e.preventDefault();
var start = $("#task_stime").val();
var end = $("#task_etime").val();
var start_time = Date.parse("1-1-2000 " + start);
var end_time = Date.parse("1-1-2000 " + end);
var checkCanAdd = myTasks.check(start_time, end_time);
if (!checkCanAdd) {
myTasks.add(start_time, end_time);
myTasks.show(); // notice you might auto-refresh withinin add
} else {
alert(checkCanAdd);
}
}
finally i got solution from my friends on below code:
function disabletime(start_time, end_time) {
var start_date = start_time;
var end_date = end_time;
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
if (tasks_array.length > 0) {
for (var i = 0; i < tasks_array.length; i++) {
var prev_s_date = new Date("January 1, 1111 " + tasks_array[i].start_time);
var prev_e_date = new Date("January 1, 1111 " + tasks_array[i].end_time);
if(end_date<=prev_e_date) {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
if(start_date<prev_e_date) {
if(start_date>=prev_s_date) {
startTimeOverlapIndex = i+1;
break;
} else {
if(end_date>prev_s_date) {
endTimeOverlapIndex = i+1;
break;
}
}
}
if(start_date.toString()===prev_s_date.toString() && end_date.toString()===prev_e_date.toString()) {
sameDateIndex = i+1;
break;
}
}
if(sameDateIndex>0) {
alert("Sorry! your time cannot be same as task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(startTimeOverlapIndex>0) {
alert("Sorry! your START time is overlaping with task ("+startTimeOverlapIndex+"), please check again!");
return false;
} else if(endTimeOverlapIndex>0) {
alert("Sorry! your END time is overlaping with task ("+endTimeOverlapIndex+"), please check again!");
return false;
} else {
//do whatever you do
return true;
}
}
return true;
}
Live link on fiddle find here
http://jsfiddle.net/mur7H/
It is 100% working. Please find below the correct answer with date and time overlapping.
function isBetween(ST, ET, PST, PET) {
var res = false;
if (((ST - PST) * (ST - PET) <= 0) || ((ET - PST) * (ET - PET) <= 0) || ((PST - ST) * (PST - ET) <= 0) || ((PET - ST) * (PET - ET) <= 0)) res = true;
return res;
}
function disabletime(start_time, end_time) {
debugger;
var start_date = new Date(start_time);
var end_date = new Date(end_time);
var disable_times = new Array();
var max_date = 0;
var min_date = 0;
var startTimeOverlapIndex = -1;
var endTimeOverlapIndex = -1;
var sameDateIndex = -1;
var resultA = true;
if (KitchenHourList.length > 0) {
for (var i = 0; i < KitchenHourList.length; i++) {
var prev_s_date = new Date(KitchenHourList[i].KitchenFromDate + " " + KitchenHourList[i].KitchenFromTime);
var prev_e_date = new Date(KitchenHourList[i].KitchenToDate + " " + KitchenHourList[i].KitchenToTime);
var STMinut = (start_date.getHours() * 60) + start_date.getMinutes();
var ETMinut = (end_date.getHours() * 60) + end_date.getMinutes();
var PSTMinut = (prev_s_date.getHours() * 60) + prev_s_date.getMinutes();
var PETMinut = (prev_e_date.getHours() * 60) + prev_e_date.getMinutes();
if (end_date <= prev_e_date) {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
endTimeOverlapIndex = i + 1;
break;
}
}
}
if (start_date < prev_e_date) {
if (start_date >= prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
startTimeOverlapIndex = i + 1;
break;
}
} else {
if (end_date > prev_s_date) {
if (isBetween(STMinut, ETMinut, PSTMinut, PETMinut)) {
{
endTimeOverlapIndex = i + 1;
break;
}
}
}
}
}
if (start_date.toString() === prev_s_date.toString() && end_date.toString() === prev_e_date.toString()) {
sameDateIndex = i + 1;
break;
}
}
if (sameDateIndex > 0) {
alert("Sorry! your time cannot be same as row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (startTimeOverlapIndex > 0) {
alert("Sorry! your START time is overlaping with row (" + startTimeOverlapIndex + "), please check again!");
return false;
} else if (endTimeOverlapIndex > 0) {
alert("Sorry! your END time is overlaping with row (" + endTimeOverlapIndex + "), please check again!");
return false;
} else {
return true;
}
}
return true;
}

Javascript Functions, Uncaught syntax error, Unexpected token?

The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}

Categories

Resources