Trying to create a JavaScript popup box - javascript

I am supposed to provide messages if the variable entered is higher or lower than a specific number.
I'm using the if statement to do this, but after the value is entered and the correct message is shown, the second 'if' statement is run too, I don't want this to happen. I've tried using the 'else' statement in place of the second 'if' statement, but it doesn't seem to work.
Here is my code
<script type="text/javascript">
var a, name;
name = window.prompt("Please enter your first name", "First Name");
a = window.prompt("Enter a number from 1-100", "1-100");
a = parseInt(a);
myFunction (a, name);
function myFunction(a, name) {
if (a <= 50) {
alert("Hey your number is less than 50");
}
if (a < 100) {
alert("Your number is higher than 50")
}
}
</script>
Please forgive me as I'm quite new to all of this.
thank you all

Thie if-else works perfectly fine for me
<script type="text/javascript">
var a, name;
name = window.prompt("Please enter your first name", "First Name");
a = window.prompt("Enter a number from 1-100", "1-100");
a = parseInt(a);
myFunction (a, name);
function myFunction(a, name) {
if (a > 0 && a <= 50) {
alert("Hey your number is less than 50");
}
else if(a <= 100){
alert("Your number is higher than 50")
}
else {
alert("Invalid number");
}
}
</script>
Again, if you look at your if conditions, both are true so it shows both the alerts.

The problem is that even if you put else if after the if statement it will also give a msg since for an example , if 40 <=50 , msg will popup .. and also 40 < 100 is true so the msg also will popup !
correct way :
if (a <= 50) {
alert("Hey your number is less than 50");
}
else if (a<=100) {
alert("Your number is higher than 50")
}

Related

How to give "No more tries left" in a password-guessing loop

I've just started learning JS and I got stuck here.
What I need to do:
If you don't enter the correct password, you get the message "Try again".
If you don't enter the password 3 times, you get the message "No more tries left".
If you enter the correct password, you get the message "You may enter".
Here's my code:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else if ( i = 0 ) {
alert("No more tries left")
} else {
alert("You may enter")
}
}
I can't get it work properly as the message "No more tries left" doesn't show up. I know ( i = 0 ) is wrong but I don't know how to make it work.
Firstly, make sure that you're not using an assignment operator when you check if i == 0. You're currently using i = 0, which doesn't check if the two are equal as much as it assigns the left to the right. No bueno.
Secondly, your for loop is off just by a bit. It'll never get to 0 because you've asked it to loop while i > 0, not i >= 0. But wait - if you use i >= 0, it'll loop four times. That's not what you want either. We'll compromise and loop three times, but check if i == 1 instead of 0.
Here's my corrected code that works:
// loop three times
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
// if it's the correct answer then alert and break the loop
if ( password.toUpperCase() == "BINGO" ) {
alert("You may enter")
break
// if it's not, and the tries has elapsed, then alert and break the loop
} else if ( i == 1 ) {
alert("No more tries left")
break
// if it's not but the tries have not elapsed, then loop again
} else {
alert("Try again")
}
}
Try this.
for ( let i = 3; i >= 0; i-- ) {
if (i===0){
alert("No more tries left");
break;
}
let password = prompt("What is the password?")
if ( password.toUpperCase() !== "BINGO" ) {
alert("Try again")
} else {
alert("You may enter")
}
}
Give the user chance to enter the password 3 times but loop 4 times and check if the loop runs for 4th times(i === 0). if prompt No more tries left and break the loop.
You are using an assignment operator instead of a comparison operator.
Change this:
else if ( i = 0 ) {
alert("No more tries left")
}
To this :
else if ( i == 0 ) {
alert("No more tries left")
}
Try this. It will run the loop until they have entered the password correctly or the number of attempts is 3.
After the loop you can then just check if valid is true or false.
let valid = false;
let attempts = 0;
do
{
const password = prompt('What is the password');
valid = password.toUpperCase() === 'BINGO';
if (!valid && attempts < 2)
{
alert('Try again');
}
attempts++;
} while (!valid && attempts < 3)
if (valid)
{
alert('You may enter');
} else
{
alert('No more tries left');
}
You are asking the user to enter the password in each iteration
using a loop. So, showing that "you don't have anymore attempt left"
is useless here. Because if the value is greater than 3, the
instruction inside the loop will not be executed.
Do not use JavaScript for authentication. It is a client side
programming language and any one who knows how things work can
extract the password. Instead use a back-end language for
authentication such as PHP, Node.js
But if you only want to know about it just for the learning purpose
not because you wanna implement it, the below code will help you
for (let i=0; i<3; i++){
let password = prompt("what is the password: ");
if (password.toUpperCase() != "BINGO"){
alert("Try Again!");
}else{
alert("You may enter!");
i=3;
}
}
There are several ways you can do the "No more attempt left" is, one of the simple and basic is:
<input type="button" value="Enter Code" onclick="checkMe()">
<script>
let i=0;
function checkMe(){
if (i<3){
let password = prompt("Enter password!");
if (password.toUpperCase() != "BINGO"){
alert("Try Again! Attempt "+ (++i));
}else{
alert("You may enter!");
i=3;
}
}else alert("No more attempts left");
}
</script>
The above code can be implemented using input field, as i said, there are several ways. Hope it helps!
Your code is fine, what goes wrong is that it does not fall into the if condition (i == 0), because the loop only runs while i > 0,
just need to adjust like this:
for ( let i = 3; i > 0; i-- ) {
let password = prompt("What is the password?")
if (password.toUpperCase() !== "BINGO" && i > 1 ) {
alert("Try again")
} else if (i == 1 && password.toUpperCase() !== "BINGO") {
alert("No more tries left")
} else {
alert("You may enter")
i = 0
}
}

The presence of a prior JavaScript event handler nullifies the next event handler

I have a strange issue where I have two event handlers for two separate buttons on two webpages. I wouldn't think that the first one would affect the second one, but when the first one is present, the second one does not fire when the connected button is pressed. When I switch the order, the first one will always fire but the second will not. If I delete the first one, the second one fires. Here is my code:
function calculateBMI() {
var weight = parseInt(document.getElementById("Weight").value);
var height = parseInt(document.getElementById("Height").value);
//Invalid input check
if (weight < 0 || weight > 750) {
alert("Weight must be greater than 0 and less than or equal to 750");
return;
}
if (height < 0 || height > 100) {
alert("Height must be greater than 0 and less than or equal to 100");
return;
}
var resultArea = document.getElementById("Result");
resultArea.value = (weight * 703) / (height * 2);
}
document.getElementById("submit").addEventListener("click", calculateBMI);
function validateInput() {
var number1 = document.getElementById("Start").value;
var number2 = document.getElementById("End").value;
if (!isNaN(number1) || !isNaN(number2)) {
alert("Sorry, you must enter a valid number");
return false
}
else if (number1 < 0 || number2 < 0) {
alert("Sorry, you must enter a positive number");
return false;
}
else if (number2 < number1) {
alert("Sorry, the second number must be greater than the first number");
return false;
}
else {
return true;
}
}
function displayPrimeNumbers() {
if (validateInput()) {
alert("Test");
}
}
document.getElementById("getPrimed").addEventListener("click", displayPrimeNumbers);
<input id="submit" type="submit" name="submit">
<input id="getPrimed" type="button" value="Get Primes" name="getPrimed">
When I press the getPrimed button, 'Test' is not outputted in the window by alert even though the validateInput function returns true. I also get this error in the firefox console from line 25 of my code (The first addEventListener):
Uncaught TypeError: document.getElementById(...) is null
I hope this is enough information to help solve my problem!
Check for the existence of the various button elements before trying to use .addEventListener()
What is happening is if the first one in your file doesn't exist, the error prevents the rest of the code executing in order to get to the next one
Simple example
var sub = document.getElementById("submit");
// null if doesn't exist, truthy element if it does
if (sub) {
sub.addEventListener("click", calculateBMI);
}

I'm having problems with my if else statement not taking the return from the if in javascript

I am trying to write this simple code for Javascript and it doesn't show me any errors in the code but when I run it the code works for the most part. It does not register the If statement but it will register the else. Everywhere I look they show me that I am basically right and I even tried different variables and Booleans but still have no luck
var userInput = prompt("Enter name");
if (userInput >= 4)
{
alert("You have a long name");
}
else
{
alert("You have a short name");
}
You need to use the String.length property to get the length of the string entered by the user.
var userInput = prompt("Enter name");
if (userInput.length >= 4) {
alert("You have a long name");
} else if(userInput.length < 4 && userInput.length > 0) {
alert("You have a short name");
} else {
alert("Name cannot be blank");
}
Read more here String.length.

Using JS to check if integer is even or pressing q to quit

The objective here is for the user to enter a number to determine whether it is even or to enter 'q' to quit the program.
var readlineSync = require('readline-sync');
var i = 0;
while (i <= 3) {
var num = readlineSync.question("Enter q to quit, or enter an integer to continue?");
if (num === 'q') {
console.log("You have quit the application. Thanks for using.");
break;
}
else if (num % 2) {
console.log("You have entered an odd number");
}
else if (num !== 'q') {
console.log("You have not entered a valid character. Please try again.");
break;
}
else {
console.log("You have entered an even number.");
break;
}
}
Pressing q initiates the appropriate response and exits the program. Entering an odd number also generates the appropriate response. However if an even number is entered, the program does not generate the appropriate response and instead reads You have not entered a valid character. Please try again. What am I overlooking? Any advice is appreciated.
It's because of your third condition (num !== 'q'). It evaluates as true when you enter an even number.

Checking if variable is an Integer in Javascript

I'm starting to learn JavaScript at school and one of the assignments require me to check user's input whether it is an Integer or not.
This code DOES NOT WORK FOR ME ON CHROME.
var person = prompt("Please enter your name", "Enter Name");
alert("Hello " + person);
var age = prompt("Please enter your age", "Enter age");
if (age == parseInt(age, 10))
alert("data is integer")
else
alert("data is not an integer")
Whether I enter a string or integer in my prompt box, it always display the "data is not an integer" message.
prompt will always return a string so in your case:
var integerAge = parseInt(age);
if(!isNaN(integerAge) && age === '' + integerAge)
alert("data is integer")
else
alert("data is not an integer")
In the case of an age, you'll also probably check it's a positive integer with some integerAge >= 0 or custom minimum and maximum in the next validation step.
Prompts always return strings, but since JS is loosely typed language, those Strings will get autocasted into Numbers when needed (Integers are called Numbers in JS), which is why your example works fine.
For a better check, you can use !isNaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
alert(!isNaN('10'));
alert(!isNaN('abc'));
alert(!isNaN(10));
For the lunatic downvoters, here's an optimized version of OP's code:
var age = parseInt(prompt("Please enter your age", "Enter age"), 10);
alert(isNaN(age) ? 'Not a number' : age);
You can try this one to check if its an integer:
function isInteger(x) {
return x % 1 === 0;
}

Categories