javascript file have error : prompt is not defined? - javascript

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()
})

Related

how to check if prompt value is a NaN and pass that information?

I've just started learning how to code in JS and I wanted to make a program that greets the user after he fills the information needed age and name.
I added a loop that checks if provided data typed in the prompt is a number but it seems to go on infinitely, like the value was always wrong and the loop looped itself over and over even if the value was right (of course after I firstly typed in the wrong value).
The best part is when I display the typeof value it shows it's right and wrong at the same time.
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = prompt("How old are you?");
usersAge = Number(usersAge);
while (Number.isNaN(usersAge)) {
let usersAge = prompt("type in the correct value?");
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
Console output:
sorry ur age is to low for us to display this website
"number"
NaN
The first issue is because you're redefining usersAge within the while block, which affects the outcome of that loop. Remove the let keyword there.
The other issue is that you're comparing strings to integers in some cases. Cast all values to the same type before comparison.
With those issues addressed your code works:
alert("Hi this site is only accsesable by pepole above an age of 18")
let usersAge = parseInt(prompt("How old are you?"), 10);
while (Number.isNaN(usersAge)) {
usersAge = parseInt(prompt("type in the correct value?"), 10);
}
if (usersAge >= 18) {
let userName = prompt("cool,what is ur name")
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
} else {
console.log("sorry ur age is to low for us to display this website")
};
console.log(typeof usersAge)
console.log(usersAge)
However putting a prompt() in a potentially infinite loop is a really bad design choice. The kind which will infuriate your users and get your site blacklisted.
A better approach would be to validate the input and if it's invalid then you should give the user the choice to cancel out of the loop and leave your site. Right now you're forcing the user to enter an age before they can leave.
Hi my friend to fix your problem you need to not use let because you use it once.
I'm going to give you the right syntax for your problem :
alert("Hi this site is only accsesable by pepole above an age of 18");
let usersAge=prompt("How old are you?");
usersAge = Number(usersAge);
while(Number.isNaN(usersAge) || usersAge === null || usersAge === '') {
usersAge= prompt("Enter your age")
}
{
if( usersAge >= 18){
let userName = prompt("cool,what is ur name");
toString(usersAge)
console.log("wassup" + " " + userName + " " + "with age of" + " " + usersAge)
}
if( usersAge < 18){
console.log("sorry ur age is to low for us to display this website");
} else{
usersAge = prompt("type in the correct value?")
}
}
I hope your problem was solved.

Javascript - Howcome .length won't detect the "t"

To summarize, for my program, I want to be able to detect the 't', and prevent the user from adding something with a quantity of '3t', '3t3', or anything of that matter.
In other words, if the quantity starts with a number, but has letters in it, it will still go through and be added, which is what I DON'T WANT.
Here's the code for where I add things. Is there any approach I should do differently?
function addProduct(){
var input = document.getElementById("productName").value;
var input2 = document.getElementById("cost").value;
var input3 = parseInt(document.getElementById("quantity").value);
var s_input3 = input3.toString();
var table = document.getElementsByTagName('table')[0];
if (isNaN(input2) || input2<0)
{
alert("not a number");
return(-1);
}
if (isNaN(input3) || input3<0)
{
alert("not a number");
return(-1);
}
// MY ATTEMPT OF DETECTING THE 't'
for (i = 0; i < s_input3.length; i++)
{
console.log(s_input3.length)
if(!(isNaN(s_input3[0]) && isNan(s_input3[i])))
{
alert("not a number")
return(-3)
}
}
You don't have to go through each of the character in the string. You can just do isNaN() on the input value.
The isNan() function does work on 3t as this code example shows. It might seem initially counter intuitive as a double negative, but the global function tests 'is not a number' so a number is false and a string true. Try code example below.
<html>
<body>
<p id="testOutput"></p>
<button onclick="testNumber()">Test is number</button>
<script>
function testNumber() {
var output = "";
 output= output + isNaN('3t') + ": 3t<br>";
 output = output + isNaN(3) + ": 3<br>";
document.getElementById("testOutput").innerHTML = output;
}
</script>
</body>
</html>
Output is:
true: 3t
false: 3
W3Schools Ref

Javascript Functions with loops assignment

I found a similar question for this same assignment but that person was using a different type of loops. I have been struggling with this assignment and even with the teacher giving me pseudo code to try to explain it further I am still having difficulties with it writing out what it's supposed to in the end.
We are supposed to create an array that holds the price of theater tickets, then make a html table that has the different level of tickets and prices that correspond with the numbers in the array. After this we prompt the user for their name and validate that they did enter something. Then we are supposed to create a function named numSeats that prompts the user for the number of
seats that they want to buy and validate that they entered a number and the maximum number of seats they can buy in one transaction is 6.
We are supposed to use a loop to
prompt the user until they enter a valid number, then create a function named seatingChoice that prompts the user for where they would like the seats to be by indicating the correct number from the table.
seartingChoice also needs to validate that they entered a number 1-4 and use a loop to prompt the user until they enter a valid number. If the user at any time hits the cancel button in a prompt we are supposed to give an alert of "Sorry you changed your mind". This is missing from my code because i haven't figured out how to do that.
When the program calculates everything and writes to the screen in the end it is supposed to write like "UsersName ordered #tickets for a total of dollaramt" but instead it writes "Null ordered null tickets for a total of $null." The following is what i have the the javascript part of the code:
var Prices = [60, 50, 40, 30];
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
function numSeats () {
var seats = prompt("Please enter the number of seats you want to buy");
parseInt(seats);
while((seats = null)||(seats > 6))
{
seats = prompt("Please enter a number between 1 and 6");
parseInt(seats);
}
return seats;
}
var seatswanted = numSeats ();
function seatingChoice () {
var choice = prompt("Please enter where you would like your seats to be located by indicating the correct number from the table");
parseInt(choice)
while((choice = null)||(choice > 4))
{
choice = prompt("Please enter a number between 1 and 4, corresponding to your section choice");
parseInt(choice);
}
return choice;
}
var seating = seatingChoice();
var dollaramt = (seatswanted * Prices[seating-1]);
document.write(Usersname + " ordered " + seatswanted + "tickets for a total of " + "$" + dollaramt + ".");
Instead of comparison operator you are using assignment operator:
var Usersname = prompt("Please enter your name");
while(Usersname = null)
{
Usersname = prompt("Please enter your name");
}
and prompt return empty string if user wont input anything so instead of null compare it to empty string i.e, ''. so change this to:
var userName = prompt("Please enter your name");
while(userName == '')
{
userName = prompt("Please enter your name");
}
There are several errors in your code. You can try your code using jsfiddle (you can try your code properly modified here: http://jsfiddle.net/pu3s0n50/).
Your errors are that you assign Username, seats and choice instead of comparing them, i.e.:
while(Usersname = null)
should be
while(Usersname == null)
and
while((seats = null)||(seats > 6))
should be
while((seats == null)||(seats > 6))
and finally
while((choice = null)||(choice > 4))
should be
while((choice == null)||(choice > 4))
The error I do not know why this happening, but this maybe solve your issue.
var Usersname = '';
Usersname = prompt('Choose a Username:');
this works. And you need the same for the others prompt.
Also if you want seat in rang 1-6: while((seats = null)||(seats > 6)) its wrong. Change to ((seats <= 6) && (seats > 0))
Maybe this could help you.
Best regards.

Can someone explain why I get "Object Required" error

"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

Code won't run due to string length issue

Got a simple Javascript program here to accept and check a password. It should:
Ask you to enter a new password
Check the strength of the password which outputs a message of either weak or strong based on a length of <6 or >6.
Get you to re enter this password to enter the 'system'
Give you simple prompts or 2 random letters if the password is not correct.
Everything works except the strong/weak checker. It has a problem getting the length of passwordEntry since it apparently doesn't exist as an entity.
Any ideas would be much appreciated
var pass;
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
var strengthCheck = new function(passwordEntry){
score = 0;
// adds to the score variable depending on the length of the password
if(passwordEntry.length > 6{
score=(score+1);
}
//reads messages back stating how strong password is based on length
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
var passContinue = prompt("Do you want to continue with this password? Yes or no?")
if(passContinue === "no" || passContinue === "No"{
main();
}
else{
pass = passwordEntry;
console.log("Your new password has been changed to " + pass);
passwordChecker(prompt("Thank You. Please Enter Your Password Below"));
}
}
var passwordChecker = function (attempt){
if(attempt == pass){
console.log("Correct password. The system has logged you on");
}
else{
//if the password is wrong, runs the incorrectpassword() function
console.log("Incorrect Password");
IncorrectPass();
}
}
}
var IncorrectPass = function (){
var clueanswer = prompt("Do You Want A Clue");
if(clueanswer === "Yes" ||clueanswer === "yes"){
console.log("I will give you two random letters");
// takes two random locations from the string array and reads them back
var randarray1 = Math.floor((Math.random()*7)+1);
var randarray2 = Math.floor((Math.random()*7)+1);
var randletter1 = pass[randarray1];
var randletter2 = pass[randarray2];
console.log(randletter1+" "+randletter2);
passwordChecker("Please try entering your password again");
}
else{
console.log("GoodBye");
}
}
main()
This part looks very wrong:
if(score=0){
console.log("Your Password is Weak");
}
else if(score=1){
console.log("Your Password is Strong");
}
You should use == or === instead of = which is used for assignment rather than comparison.
This doesn't make sense either:
var main = function(){
strengthCheck((prompt("Please Choose a New Password to Begin"));
}
There are three opening parentheses and only two closing ones. Smells like parser error.
Change this...
var strengthCheck = new function(passwordEntry){
to this...
var strengthCheck = function(passwordEntry){
When you use new, you're not using it to create a new function. You're using it to call the function as a constructor, which will return an object. (An empty object in your case.)
Also, you have many syntax errors in your code. Use a code validator like http://jshint.com as well as a beautifier like http://jsbeautifier.org to clean up your code.

Categories