javascript if number is evenly divisible true if not false - javascript

I have to write Java script that can read two integers from the user, if the first number the user entered is evenly divisible by the second number, then it will display an alert of TRUE to the user, and FALSE otherwise. If either number the user enters is ZERO the alert should display FALSE to the user.
this is my code it does not work
var y = prompt("Enter a Value","");
var z = prompt("Enter a Value","");
if (y % z === 0) {
greeting = "TRUE";
} else (y % z !== 0 ||
{
greeting = "FALSE"
document. get Element By Id ("true false").inner HTML = greeting;

If either number the user enters is ZERO the alert should display
FALSE to the user.
change you if condition to
if (x && y && y % z === 0) {
Rest of the code is
if (x && y && y % z === 0)
{
greeting = "TRUE";
}
else
{
greeting = "FALSE";
}

If you are new to javascript here is another way to implement this very common pattern using the ternary operator:
var greeting = (x && y && y % z === 0) ? "TRUE" : "FALSE";

Related

JavaScript if/else Statement Input Data [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Please help me, I am studying on my own and need help, I want to create an "JavaScript else if statement" but this doesn't work.
Who wants to make input
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 100, output "+"
// If "x" is greater than or equal to 11 and "x" is less than 100, and "y" is equal to 100, output "++"
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 1, output "+++"
// If "x" is greater than or equal to 10, and "y" is equal to 1, output "++++"
The code that I tried to make, below
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Full Working Code:
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Explanation:
You were using || which means or in logical statements, where you meant to use && to represent and.
Furthermore, when using logical statements, more than or equal to would be represented by >= and not >.
What you used:
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
What you were supposed to use:
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
To learn more about JavaScript Operators and Comparison Logical Operators (i.e. ||, &&, >, >=, == or !=), visit:
https://www.w3schools.com/js/js_comparisons.asp
https://www.w3schools.com/jsref/jsref_operators.asp
Recommended changes to code:
I would strongly recommend adding an else statement to the conditional statement in you code, as then if all other conditions don't apply there will be a back-up, and your code will not error out and print out undefined.
first: the OR - || opartor returns true even if only one of the expression in is both sides are true. the AND - && operator returns true only if both of them are true, and this is what you are looking for.
so you have to replece all the OR opartors with AND operators.
second: to check if a value is greater than or equal to another value, you have to combine both operators > and = together.
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}

validation not working in program is you enter an invalid response and wrong alert coming up for another prompt

function studentName(x) {
while (x == '' || x >= 0 || x < 0) {
if (x == '') {
x = prompt('Cannot leave field blank. Enter again');
} else if (x >= 0) {
x = prompt('Cannot Enter a number. Enter again')
} else {
x = prompt('Cannot Enter a number. Enter again')
}
}
return (x)
}
function studentScore(y) {
while (y == '' || y > 100 || y < 0 || isNaN(y)) {
if (y == '') {
y = parseFloat(prompt("Cannot leave field, blank please enter students score"));
} else if (y > 100 || y < 0) {
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
} else {
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
}
return (y)
}
function another(z) {
while (z == '' || z != 'n' && z != 'N' && z != 'y' && z != 'Y') {
if (z != 'n') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'N') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'y') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z != 'Y') {
z = prompt('Invalid Option. Enter another score Y or N')
} else if (z == '') {
z = prompt('Invalid Option. Enter another score Y or N')
}
}
return (z)
}
var names = []
var scores = []
var redo = true
var anotherName
var redo2
var retry = true
var anotherScore
var retry2
var i = 0
var a = 1
var score = 0
while (redo == true) {
var studentNames = prompt('Enter student name');
var name = studentName(studentNames);
names.push(name)
while (retry == true) {
var studentScores = parseFloat(prompt('Enter student score'));
score = score + studentScore(studentScores);
retry = prompt('Enter another score? Y/N');
retry2 = another(retry);
if (retry == 'y' || retry == 'Y') {
retry = true
a++
} else if (retry == 'n' || retry == 'N') {
retry = false
}
}
score = score / a
scores[i] = score
redo = prompt('Enter another student? Y/N');
redo2 = another(redo);
if (redo == 'y' || redo == 'Y') {
redo = true
retry = true
i++;
a = 1
score = 0
} else if (redo == 'n' || redo == 'N') {
redo = false
}
}
var message = ""
for (y = 0; y < names.length; y++) {
alert(names[y] + " - " + scores[y]);
}
when asked if the person wants to enter another score and Y or N and i enter something x i do get a prompt that says enter another score but once i say yes instead of asking for the score it goes straight into asking if i would like to enter another student instead of asking for the score also when you enter something that should be invalid you get stuck with the same problem but a bit diffrent first off it says invalid enter another score not another student and when you enter Y for yes it stops the program a
thanks for the help!
it would probably be best to run the program a bit to fully grasp the issue it is difficult to explain the problem.
Your main problem is these 3 lines
retry = prompt('Enter another score? Y/N');
retry2 = another(retry);
if(retry == 'y' || retry == 'Y')
{
...
You are only using the first input (retry) in your if statement (which can be bad input). If it is bad input retry2 will hold the valid input (but you don't use that in your if condition).
You are ignoring the second attempt and using the first invalid input which exits your student score while loop because retry is bad input and not true anymore.
You can fix this by just changing retry2 = another(retry); to retry = another(retry);
I would also suggest using separate variables for the while statement and your prompt variable.
it also looks like you will have the same problem with redo and redo2

how to combine elements of array into one alert box at the end

I have a program that calculates students percentages in a class and need the final output to all be in one box. however my program currently does on alert box for each student how do I fix this?
here is the code
<script>
function studentName(x)
{
while(x == '' || x >= 0 || x < 0)
{
if(x == '')
{
x = prompt('Cannot leave field blank. Enter again');
}
else if (x >= 0)
{
x = prompt('Cannot Enter a number. Enter again')
}
else
{
x = prompt('Cannot Enter a number. Enter again')
}
}
return(x)
}
function studentScore(y)
{
while(y == '' || y > 100 || y < 0 || isNaN(y))
{
if (y == '')
{
y = parseFloat(prompt("Cannot leave field, blank please enter students score"));
}
else if (y > 100 || y < 0)
{
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
else
{
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
}
return(y)
}
function another(z)
{
while(z == '' && z != 'n' && z != 'N' && z != 'y' && z != 'Y')
{
while (z == '' && z != 'n' && z != 'N' && z != 'y' && z != 'Y' )
{
z = prompt('Invalid response, would you like to enter another score Y/N ')
}
while(z == 'n' || z == 'N')
{
Z = prompt('Would you like to enter another student')
}
while (z == 'y' || z == 'Y')
{
z = prompt("Enter another score")
}
}
return(z)
}
var names = []
var scores = []
var redo = true
var anotherName
var redo2
var retry = true
var anotherScore
var retry2
var i = 0
var a = 1
var score = 0
while(redo == true)
{
var studentNames = prompt('Enter student name');
var name = studentName(studentNames);
names.push(name)
while(retry == true)
{
var studentScores = parseFloat(prompt('Enter student score'));
score = score + studentScore(studentScores);
retry = prompt('Enter another score? Y/N');
retry = another(retry); /**/
if(retry == 'y' || retry == 'Y')
{
retry = true
a++
}
else if(retry == 'n' || retry == 'N')
{
retry = false
}
}
score = score / a
scores[i] = score
redo = prompt('Enter another student? Y/N');
redo = another(redo); /**/
if(redo == 'y' || redo == 'Y')
{
redo = true
retry = true
i++;
a = 1
score = 0
}
else if(redo == 'n' || redo == 'N')
{
redo = false
}
}
var message = ""
for(y=0; y < names.length; y++)
{
alert(names[y] + " - " + scores[y]);
}
again I have a program that calculates students percentages in a class and need the final output to all be in one box. however my program currently does on alert box for each student how do i fix this and get all of the students names into one final alert box?
You are getting separate alerts because you're calling alert on every iteration with individual values. One solution could be to combine the names and the corresponding scores in a new array and call alert once on this array. Using join('\n') on the new array will convert the array elements to string and separate each array elements with new line, for the sake of formatting. Just change the last part with:
let roster = [];
for(let y=0; y < names.length; y++) {
roster.push(names[y] + " - " + scores[y]);
}
alert(roster.join('\n'))
Better yet if you save names and scores in one array from the beginning, like the roster. In this way you could avoid additional iteration at the end.

How to clear text field using javascript with a condition?

I want if I clear the text field #t1, text field #d1 should clear. But last two lines dont do it....
function utl()
{
var a = document.getElementById('t1');
var z = document.getElementById('d1');
if (a!=0)
{
var y = parseFloat(a.value) * 100;
y = y || 0;
z.value = y.toFixed(2);
}
else if (a==0)
z.value = 0;
else if (a=='')
z='';
a is a DOM element, and so it will always be != 0 as the != operator will coerce it to a string, and then to a number, and that number will be != 0.
You probably wanted to use the .value property:
var a = document.getElementById('t1').value;
But you'd still have a problem: The value of an input is always a string. In JavaScript, the == and != operators do type coercion, and "" is == 0. So your third statement, z='', will never be reached.
You can use the strict equality operators to figure out what's going on:
var a = document.getElementById('t1').value;
var z = document.getElementById('d1');
if (a === "") { // <== Note! === rather than ==
z.value = "";
} else {
a = +a; // Convert to number intentionally
if (a != 0) {
var y = a * 100;
y = y || 0;
z.value = y.toFixed(2);
} else if (a == 0) {
z.value = "0";
}
}
The strict equality (===) and inequality (!==) operators don't do type coercion, so although "" == 0 is true, "" === 0 is false.
That line where I converted to a number:
a = +a;
...is only one of the many options available. Using +str to convert to a number is the strictest way, but you don't have direct control over the number base. You could also use:
a = parseInt(a, 10); // If you're expecting an integer, or
a = parseFloat(a); // If it may have a fractional portion
...assuming you want base 10 (decimal), but note that they ignore trailing characters, and so parseInt("123laksdjflk", 10) is 123. In contrast, +str (or Number(str)) will say that's Nan because they consider the entire string, not just the first part.

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources