How to handle Cannot read properties of undefined (reading '0') error? - javascript

How to handle Cannot read properties of undefined (reading '0'). I want to trigger this in ajax success of select onchange.
var date_sched = [];
const output = {
[date_sched[0].user_id]: date_sched[0].dates,
};
//var doctor_dates;
$("#schedDay").on("show.datetimepicker update.datetimepicker",
function() {
highlight();
});
function highlight() {
// var dateToHilight = text;
var dateToHilight = output;
var array = $("#schedDay").find(".day").toArray();
for (var i = 0; i < array.length; i++) {
var date = array[i].getAttribute("data-day");
if (dateToHilight[doctor_dates].indexOf(date) > -1) {
array[i].classList.add('highlighted');
}
}
}

Related

Accessing an objects property inside a function

I'm trying to access objects properties inside an array in my code to render the text values of input boxes restored after a refresh from the local storage but for some reason when I try to run the for loop inside my appStart() function it gives me: "Uncaught TypeError: Cannot read property 'id' of undefined at appStart". Any insiights of why this happens and how to fix it will be greatly appreciated.
const currentDayPlaceholder = $("#currentDay");
const timeInTimeBlocks = $(".input-group-text");
const timeBlockInput = $(".form-control");
const saveButton = $(".saveBtn");
let numericCurrentTime = parseInt(moment().format("H A"));
let notes = [];
currentDayPlaceholder.append(moment().format('dddd, MMMM Do'));
function timeBlocksColorDeterminator() {
for (let i = 0; i < timeInTimeBlocks.length; i++) {
let numericTimeinTimeBlock = parseInt($(timeInTimeBlocks[i]).text());
if ($(timeInTimeBlocks[i]).hasClass('pm')) {
numericTimeinTimeBlock += 12;
}
if (numericCurrentTime === numericTimeinTimeBlock) {
$(timeBlockInput[i]).addClass("present");
} else if (numericCurrentTime > numericTimeinTimeBlock) {
$(timeBlockInput[i]).addClass("past");
} else {
$(timeBlockInput[i]).addClass("future");
}
}
}
function appStart() {
notes = JSON.parse(localStorage.getItem("timeBlockNotes"));
for (let i = 0; i < timeBlockInput.length; i++) {
if (i === parseInt(notes[i].id)) {
timeBlockInput[i].value = notes[i].value;
}
}
}
appStart();
saveButton.on("click", function () {
console.log("click");
notes.push({
value: timeBlockInput[this.id].value,
id: this.id
})
localStorage.setItem("timeBlockNotes", JSON.stringify(notes));
})
timeBlocksColorDeterminator();
I have fixed this after changing my appStart() function to this :
function appStart() {
notes = JSON.parse(localStorage.getItem("timeBlockNotes"));
for (let i = 0; i < notes.length; i++) {
timeBlockInput[parseInt(notes[i].id)].value = notes[i].value;
}
}
thank you guys for your comments and answers.

JS queue array debug error

I am receiving this error,
Practice.html:formatted:20 Uncaught TypeError: queueArray.push is not a function
at Queue.add (Practice.html:formatted:20)
at Practice.html:formatted:30
but push isn't supposed to be a function. It is supposed to be a method executed on an array. So what could this mean??
var tickerArray = ['BP', 'AMZN', 'EARK'];
//also tried putting queueArray here because that would make it global, so i guess it isnt a scope issue?
function Queue() {
this.top = 0; //first item in the stack
var queueArray = []; //array to hold items
}
Queue.prototype.add = function(obj) {
queueArray.push(obj);
}
Queue.prototype.get = function() {
return queueArray.splice(this.top, 1);
}
var queueArray = new Queue();
for (i = 0; i < tickerArray.length; i++) {
queueArray.add(tickerArray[i]);
}
console.log(q.get());
Set queueArray as this.queueArray and return this.queueArray from .get()
var tickerArray = ['BP', 'AMZN', 'EARK'];
function Queue() {
this.top = 0; //first item in the stack
this.queueArray = []; //array to hold items
}
Queue.prototype.add = function(obj) {
this.queueArray.push(obj);
}
Queue.prototype.get = function() {
this.queueArray.splice(this.top, 1);
return this.queueArray; // `return` `this.queueArray` from the function
}
var queueArray = new Queue();
for (i = 0; i < tickerArray.length; i++) {
queueArray.add(tickerArray[i]);
}
console.log(queueArray.get());

Error after insert HTML code in DOM in console (Chrome browser)

Get HTML in line: room["html"] = $(this).parents(".selectRowRoom").html(); and insert after load step-02.php in .thisRoom but this error is in Console.
$(function () {
var hotel = [];
var lenHotel = 0;
$('#forPrice').on('click', function() {
$('select').each(function() {
if($(this).val() > 0 && $(this).val() < 10) {
var room = {};
room["room"] = $(this).attr('room');
room["price"] = $(this).attr('price');
room["val"] = $(this).val();
room["html"] = $(this).parents(".selectRowRoom").html();
hotel.push(room);
}
});
lenHotel = Object.keys(hotel).length;
console.log(hotel);
});
$('#forPrice').click(function () {
$('#Step-01').hide();
$('#Step-02').show();
$('.hiddenAndShow').hide();
$( "#Step-02" ).load( 'step_02', function () {
for(var i = 0; i <= lenHotel; i++) {
$("#Step-02").find('.thisRoom').append("<tr class=\"selectRowRoom\">");
$("#Step-02").find('.thisRoom').append(hotel[i]['html']);
$("#Step-02").find('.thisRoom').append("</tr>")
}
});
});
})
And error in console is:
Uncaught TypeError: Cannot read property 'html' of undefined
This...
for(var i = 0; i <= lenHotel; i++)
Should be this
for(var i = 0; i < lenHotel; i++)
Your accessing an element in the array that doesnt exist.

Get the document object of an IFrame in PhantomJS?

I am trying to get the document of an Iframe after setting the iframe.src.
I am calling this in phantom-node.
The function returns an error when the iframe is empty:
fetchGuestbookEntries: function () {
var getGuestbookForPage = function (doc) {
var result = [];
var rows = doc.querySelectorAll('td[class="guestbook"]');
var date = "";
var entry = "";
for (var i = 0; i < rows.length; i++) {
date = i % 2 == 0 ? rows[i].innerText : date;
entry = i % 2 != 0 ? rows[i].innerText : entry;
if (date && entry) {
var info = date.split('\n').map(function (elem) {
return elem.replace('\n', '').trim();
});
result.push(
{
info: {
guestname: info[0],
date: new Date(info[3]).toISOString().slice(0, 10),
time: info[4].replace(/Uhr|h/gi, '').trim()
},
entry: entry.trim()
}
);
date = "";
entry = "";
}
}
return result;
};
var getPaginationSize = function () {
return document.querySelector('td[class="guestbook_navijump"]') ?
document.querySelector('td[class="guestbook_navijump"]').querySelectorAll('a').length : 0;
};
var getIframeDoc = function(ifrm) {
return ifrm.document ||
ifrm.contentDocument ||
ifrm.contentWindow.document;
};
var pagination = getPaginationSize();
var entries = [];
for (var i = 0; i <= pagination; i++) {
var paginationPageUrl = window.location.href + "?jump=" + i;
var iframe = document.createElement('iframe');
iframe.src = paginationPageUrl;
var doc = getIframeDoc(iframe);
entries.push(getGuestbookForPage(doc));
}
return entries;
}
Is there a way to get the document?
The error:
Uncaught TypeError: Cannot read property 'document' of null
at <anonymous>:2:21
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
I normally open the Page in PhantomJS.
You should be able to get it with this
document.getElementById('myframe').contentWindow.document

Deleting from an array doesn't work

So, I'm trying to delete from an array if it's element value isn't equal to a value that I specified:
Code: http://pastebin.com/hUc3mVLv
$scope.enablePVR = function()
{
for (i = 0; i < $scope.new_epg.length; i++) {
start_time = convert_time($scope.new_epg[i].start);
$scope.new_epg[i].title = $scope.new_epg[i].title.replace(/<(?:.|\n)*?>/gm, '');
$scope.new_epg[i].description = "";
$scope.new_epg[i].time = start_time;
}
archiveEPG = [];
for(var i=0; i<archiveEPG.length; i++) {
var e = document.getElementById("dateSelect");
if($scope.new_epg[i].start.split(" ")[0] == e[e.selectedIndex].value) {
archiveEPG[archiveEPG.length+1] = $scope.new_epg[i];
}
}
document.getElementById("dateSelect").remove(0);
$scope.get_epg(null, true, archiveEPG);
}
.remove(0) isn't valid you can add this function to make it valid tho :
Array.prototype.remove = function(index) {
return this.splice(index, 1); // The second parameter is the number of elements to remove.
}

Categories