Can someone explain why I get "Object Required" error - javascript

"I posted a similar question the other day and Thanks to #Alnitak for helping! However, I'm trying to enable/disable/enable 2 links (a href) between 2 given times and receive the "Object required" error. It's like the id's used lose focus. page_load function is called via onload. nStart & nExpired equal Start and End times and I'm using SetInterval instead of setTimeout (I modified Alnitak's code).
I wouldn't have a problem if these were buttons or if I could use PHP, but 'powers that be' would like it via hyperlink. Please tell me it's possible.. LOL
The error occurs the first line of the second IF condition i.e. making link visible.
var myInterval;
function page_load() {
myInterval = setInterval(function(){ShowLink()},60000);
}
function ShowLink() {
var now = new Date();
var clock = now.toTimeString();
var nStart = 1310;
var nExpired = 1312;
var MigTime = 60 * now.getHours() + now.getMinutes();
var disable = (day === 0 && (MigTime >= nStart && MigTime < nExpired));
if (disable == true) {
//hide links
document.getElementById("prdlnk").style.visibility = "hidden";
document.getElementById("viewlnk").style.visibility = "hidden";
document.getElementById("MigMsg").innerHTML= "Scheduled Migration in Progress. Please try later.";
}
if (MigTime > nExpired) {
//visible
document.getElementById("prdlnk").style.visibility = "visible";
document.getElementById("viewlnk").style.visibility = "visible";
document.getElementById("MigMsg").innerHTML= "";
// clearInterval(myInterval);
}
}
Thanks in advance,
Vernon

Could be a bad copy paste, but this line is missing a '
document.getElementById(prdlnk').style.visibility = "visible";
Should be
document.getElementById('prdlnk')...
Also, why are you mixing quotes and double quotes? Pick a style and stick with it.

var disable = (day === 0 && (MigTime >= nStart && MigTime < nExpired));
In this line of code, what is the intent behind day === 0? === is a test for object type and value, it's not an assignment operator. try day = 0

Related

javascript file have error : prompt is not defined?

I am newbie with javascript and I am writing a very simple javascript according to the textbook and here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):") // prompt instead of promt
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);
Then, I installed nodejs, and tried to run this file by many ways. but it said to me many error.
The 1st error is, when I ran it directly
Object expected
800A138F
microsoft jscript runtime error
the second error is, when I ran it by the command node battleship.js, here is the error
As you can see in the picture, it said to me that promt is not defined.
My problem is, I ran another code no problem. Which means nodejs no problem.
And, I ran my code online no problem, which means my code no problem.
So, how can I fix this one ? Could you please help me with this ? Thank you very much for your time.
Node.js isn't the same as running javascript in the browser, it doesn't have the window object, which has things like prompt() or alert(). in browsers, those show up as a pop-up.
Instead of alert(), you can probably just use console.log(), and for prompt(), you can look at this https://nodejs.dev/learn/accept-input-from-the-command-line-in-nodejs
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
})
readline.question(`What's your name?`, name => {
console.log(`Hi ${name}!`)
readline.close()
})

Javascript stop setInterval

if (document.case.display.value.length >16 && document.case.display.value.length < 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length > 20) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 25 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
}
else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}}
window.setInterval(function(){
testLength();
}, 100);
Notiflix is a JavaScript library for notification.
I have a display who font go down if have so much characters and i set time every 0.1 second he check number of characters. If number is higher than 16 he put a notification.
But he put every 0.1 second notification i want only one time/s. Do you have idea who can "block " this line of code for 10 second and after that read this without moving settimer down.
Sorry about bad English.
Any information will help me
You can try storing your setInterval() in a variable and calling it only when required. Else, you can stop that using that variable name.
let myInterval;
function start(){
myInterval = window.setInterval(function(){
testLength();
}, 100);
}
function stop(){
clearInterval(myInterval);
}
P.S: I would also like to advice on using onChange eventListener for checking test length rather than setInterval.
Update: Alternate method
You can also try removing setInterval thing and adding something like this:
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit")
console.log("numbers", numbers);
numbers.forEach(el => el.addEventListener('click', testLength))
});

Is it possible to extract time from a text comment using js?

First let me apologize for my ignorance when it comes to js.
Is it possible to extract a time from text? For example, i'd like to extract the time from the following text "Results phoned by _ to _ at 2018/04/12 01:31:33. Results confirmed. Read back."
Is this even possible to accomplish this? The software that I use allows for both js and BIRT coding. Any help would be appreciated.
var str = dataSetRow["Comment - Result"];
var time = str.match(/([0-1]\d|2[0-3]):([0-5]\d):([0-5]\d)/g);
time;
Outputs to "Ljava.lang.Object;#bd6334" and i have no idea how to fix it.
I get the "Ljava.lang.Object;#" error for every row of my table with different characters after the #
If I change the code to:
var str = dataSetRow["Comment - Result"];
var time = str.match(/\d{2}:\d{2}:\d{2}/g);
if (time.length>0) time [0];
else "";
I get the desired result but it will only display 1 row of a table with significantly more rows. Am I missing something?
Managed to get it working with some help from our system's manufacturer:
var str = dataSetRow["Comment - Result"];
var time = null;
if (str != null) time = str.match(/\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}/);
var output = "";
if (time != null) {
for (var i = 0; i < time.length; ++i) {
if (i > 0) output += "\n"; // this adds a line break in a computed column expression
output += time[i];
}
}
output;

How to retrigger a function with timeOuts via key input

For some time already I'm struggling with following code:
$(document).ready(function(){
keyBind();
});
var set = [];
var start = 0;
var total = 3;
var timeout = 1000;
function displayImages(i, total){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img class="image" src="' + imgPre + i + imgExt +'">';
var sndSrc = new Audio(imgPre + i + sndExt);
var magic = ((i+1)%total) + ',' + total;
sndSrc.play();
pixBox.append(imgSrc);
var sT = setTimeout('displayImages(' + magic + ')', timeout);
set.push(sT);
if(sT >= total+1){
sndSrc.pause();
}
if(sT === total+1){
clearTimeout(sT);
// $('img').remove();
$('img:not(:last-child)').remove();
}
return false;
}
function keyBind(){
$(document).keydown(function(e) {
switch (e.which) {
case 75: //k
displayImages(start, total);
break;
case 80: //p
clearTimeout(set);
break;
default:
return;
}
e.preventDefault();
});
}
It's a kind of very primitive slideshow with accompanying sound files for each picture/slide. As you can see, it's controlled by keyboard input (keyBind function). And it all works fine, but only for the first time. When I trigger it fresh, timeOut function is doing it job and both if statements (first responsible for cutting the sound after the last file, second responsible for wrapping images back to first one after last is displayed) are fireing up and all is well.
That is, until I want to restart the sequence again, without refreshing. If I do that, soundfiles are going mute and the image sequence turns into an endless loop.
I've already tried dividing start and stop of sequence in separate functions, I tried to clear the div and reset the sound at the start of sequence and I did tried reseting the timeOut at the beggining too. All to no avail.
Do you, good and dear people of SO, have any idea what's wrong with my code and can shed some light on it? It's gonna be a lifesaver.
EDIT
It looks like setTimeout(sT) is not working. I've put a console.log after it and sT is not 0, it still has ID of last iteration. What may be the cause? What am I doing wrong?
Some issues:
You use the value that setTimeout returns as if it has some meaning (incremental), but the
actual value is implementation dependent. You should only use it for passing it to clearTimeout,
but not for things like the following:
if(sT >= total+1)
It is also not clear why you would want to add them to the set array,
as only the last one really is pending. All the others have already expired, since you
"chain" calls to setTimeout.
You clear a time-out right after setting one, while there is nothing you did not already know when setting it. So why not avoiding the setTimeout when you would be clearing right after?
Also, the argument to clearTimeout should be a number. It cannot be an array like set:
case 80: //p
clearTimeout(set);
You have a start variable, but ignore it when doing (i+1)%total.
Although not a problem here, you should avoid using strings as arguments to setTimeout, as it is just as evil as eval that way.
Here is a version of your code that fixes several of these issues:
$(document).ready(function(){
keyBind();
});
var sT = -1;
var total = 3;
var timeout = 1000;
function displayImages(i){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img class="image" src="' + imgPre + i + imgExt +'">';
var sndSrc = new Audio(imgPre + i + sndExt);
i = (i+1)%total;
sndSrc.play();
pixBox.append(imgSrc);
if(i == 0){
sT = -1;
sndSrc.pause();
$('img:not(:last-child)').remove();
} else {
sT = setTimeout(displayImages.bind(null, i), timeout);
}
return false;
}
function keyBind(){
$(document).keydown(function(e) {
switch (e.which) {
case 75: //k
displayImages(0);
break;
case 80: //p
clearTimeout(sT);
break;
default:
return;
}
e.preventDefault();
});
}
I am not quite sure when you actually want to stop the sound and remove the images (except one). You might still need to change this code a bit.
EDIT: Adjusted according to correcting comment below:
You should not pass arguments to a function directly using settimeout. This has bugged me out a number of times. See this old post for a solution to this particular part of your code: How can I pass a parameter to a setTimeout() callback?

Improve this search engine detecter with javascript

I have the following code which detects which search engine and what search term has been used:
if (document.referrer.search(/google\.*/i) != -1) {
var start = document.referrer.search(/q=/);
var searchTerms = document.referrer.substring(start + 2);
var end = searchTerms.search(/&/);
end = (end == -1) ? searchTerms.length : end;
searchTerms = searchTerms.substring(0, end);
if (searchTerms.length != 0) {
searchTerms = searchTerms.replace(/\+/g, " ");
searchTerms = unescape(searchTerms);
alert('You have searched: '+searchTerms+' on google');
}
}
That actually works, but unfortunately it doesn't work as expected sometimes.
Sometimes if the referrer was even not google i get an alert with the search term as : ttp://www.domain.com ( without H at the start ) i think that may lead to the bug.
Appreciate any help!
Have you tried leveraging existing JS URL parsing schemes? It might save you a bunch of time. For example:
http://blog.stevenlevithan.com/archives/parseuri
It's cutting the "h" off because q= was not in the referrer string. So your start variable is -1. Then you add 2 to that to get your searchTerms var with a substring. You need to check for start to be equal to -1 and return.
I also think your "google" string detection is not bulletproof, I would rather do something like this...
var ref = document.referrer;
var pcol = ref.indexOf("://") + 3;
if(ref.indexOf("google.com") == pcol || ref.indexOf("www.google.com") == pcol) {
// It is google
}
One last thing, you should use decodeURIComponent instead of unescape.

Categories