Input validation only working once - javascript

I am trying to create a script that will take 2 inputs and calculate the sum. I would like both inputs to be validated before the calculation takes place - inputs must range between 0 and 10.
However when I input values over 10 in both fields (e.g. 50), I am only getting one validation error instead of two.
What could be wrong?
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
} else if (isNaN(y) || y < 0 || y > 10) {
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
} else {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
<p>Please input a number between 0 and 10:</p>
1st number:<input id="val01" required> <b id="validation1"></b> <br>
2nd Number:<input id="val02" required> <b id="validation2"></b> <br>
<button onclick="calc()">click</button><br /> sum = <span id="total">0</span>

You could use a flag and check it for the calculation.
Skip the else parts and use the flag instead.
var ok = true;
if (isNaN(x) || x < 0 || x > 10) {
ok = false;
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
}
if (isNaN(y) || y < 0 || y > 10) {
ok = false;
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
}
if (ok) {
z = x + y;
document.getElementById("total").innerHTML = z;
}

If your first validation fails (if (...)), you do not execute the second validation (else if (...)) anymore.
Instead, run the validations separately from each other and only do the calculation if both succeed, e.g.:
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
var valid = true;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
valid = false;
}
if (isNaN(y) || y < 0 || y > 10) {
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
valid = false;
}
if(valid) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}

You only get one validation because of the way your logic inside the if else statement is built.
You only go "inside" one of the three statements, because you're using if else if, when you need to go inside multiple ones, you can just use a sequence of if()
<script>
function calc() {
var x, y, z, text1, text2;
// Get the value of the input field with id="numb"
x = Number(document.getElementById("val01").value);
y = Number(document.getElementById("val02").value);
var invalidX = true;
var invalidY = true;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 0 || x > 10) {
invalidX = false;
text1 = "Input not valid";
document.getElementById("validation1").innerHTML = text1;
}
if (isNaN(y) || y < 0 || y > 10) {
invalidY = false;
text2 = "Input not valid";
document.getElementById("validation2").innerHTML = text2;
}
if (invalidX && invalidY) {
z = x + y;
document.getElementById("total").innerHTML = z;
}
}
</script>
Hope that is what you were looking for. Notice that I also included two variables with booleans that control if the input is valid.

Remove the else if condition in your code for the second valida ation that u are doing.

Related

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.

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.
What should I do in order to get the code to recognize 0 as a value?
var x =
this.getField("1_7").value;
var y =
this.getField("2_7").value;
var z =
this.getField("3_7").value;
var f = Math.floor((this.getField("Des Temp").value - 10) / 2);
var temp;
if(!x)
{
x = f;
}
if(!y)
{
y = f;
}
if(!z)
{
z = f;
}
if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;
if(f > temp)
f = temp;
if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}
O is a "falsy" value so
if(!x)
Is doing what it is supposed to do. The empty value is probably an empty string so you could do
if ( ! x.length )
instead.
$('#x').on( 'input', function() {
console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >
It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.
var x = 0;
var y = 5;
var z = 3;
var f = 10;
if(0)
{
console.log("0 is false");
}
if(1)
{
console.log("1 or any number != 0 is true");
}
if(x.length)
{
x = f;
console.log("x is not set");
}
if(y.length)
{
y = f;
console.log("y is not set");
}
if(y.length)
{
z = f;
console.log("z is not set");
}

Jquery array querying not working

So I have to pares through an array and it's multiple variables and input them on separate lines.
Here is the code:
while (array[x] != null) {
y = 0;
y = x;
alert(y + 'y');
setTimeout(function() {
if (y == 0 || y % 3 === 0) {
var namestring = array[y];
var namestring = namestring.replace('[','');
var namestring = namestring.replace('[','');
var namestring= namestring.replace('"', '');
var namestring= namestring.replace('"', '');
}
if (y % 2 != 0 || y % 3 != 0 && x > 0) {
var date = array[y]
var date = date.replace('"', '');
var date = date.replace('"', '');
}
if (x % 2 == 0 && x > 0) {
var text = array[y];
var text = text.replace('"', '');
var text = text.replace('"', '');
var text = text.replace("]", '');
var text = text.replace("]", '');
createcard(namestring,date,text);
}
}, 500);
if (x > 500) {
break;
};
x++;
alert(x + 'x');
}
The alerts are simply for debugging. Anyway, my variables, for example namestring gets returned as undefined. However, if I change the line to say array[0] instead of array[y], it works, even if y is set to 0...
You're assigning
y = 0;
and
y = x;
x appears to be undefined in that code snippet but maybe it is part of a larger batch of code. It basically looks like you're overwriting y with the value of x?

JavaScript function, if else, isNaN

I've tried to make a function where you're supposed to enter two numbers in two different boxes and loop it until you put in a valid number!
var x = parseInt(prompt("Please enter a number!"));
var y = parseInt(prompt("Please enter a number!"));
function add(x, y) {
var z = x + y;
var i = false;
do {
if (isNaN(x)) {
alert("Invalid entry. Please enter a number!")
} else if (isNaN(y)) {
alert("Invalid entry. Please enter a number!")
} else {
alert(x + " + " + y + " = ");
i = true;
}
while (i == false);
}
}
add(x, y);
There are a couple of problems with this code:
Your while is misplaced.
The parameters x and y don't make sense, because the user needs to input them.
The prompts asking for the numbers are outside of the loop.
Here is the fixed code:
function add() {
do {
var x = parseInt(prompt("Please enter a number!"));
var y = parseInt(prompt("Please enter a number!"));
var z = x + y;
var i = false;
if (isNaN(x)) {
alert("Invalid entry. Please enter a number!")
} else if (isNaN(y)) {
alert("Invalid entry. Please enter a number!")
} else {
alert(x + " + " + y + " = " + z);
i = true;
}
}
while (i == false);
}
add();
There are a couple of issues:
It's syntactically invalid. You've ended up with a free-standing while (i == false); (which would fine, but it would never end if i is ever false) and a dangling } under your code. You need to move the while line beneath the closing } of the do.
If x or y is NaN, your add function loops until they change...but no code in that loop ever changes them.
I don't know what you want add to do (since just adding numbers doesn't require a function), but if the goal is to keep prompting the user, you have to move the prompts into the loop:
function add() {
var x, y, z;
var valid = false;
while (!valid) {
x = parseInt(prompt("Please enter a number!"));
y = parseInt(prompt("Please enter a number!"));
valid = !isNaN(x) && !isNaN(y);
if (!valid) {
alert("Invalid entry. Please enter a number!")
}
}
z = x + y;
// Do something with z
}
add();
You can also do it recursively without using a do while loop at all, by asking x and y values until both are correct. Also, note that I used a radix value of 10 for parseInt(string, radix);, the reason being that the documentation describes radix as:
An integer that represents the radix of the above mentioned string.
Always specify this parameter to eliminate reader confusion and to
guarantee predictable behavior. Different implementations produce
different results when a radix is not specified.
See more from the documentation of parseInt.
The code example:
function askXY(x, y) {
var x_ = x,
y_ = y;
if(typeof x_ === "undefined") {
x_ = parseInt(prompt("Please enter a number for x!"), 10);
}
if(typeof y_ === "undefined") {
y_ = parseInt(prompt("Please enter a number for y!"), 10);
}
if(isNaN(x_) || isNaN(y_)) {
alert("Invalid entry. Please enter a number!");
// The magic is here, we keep the x or y if either one of those are correct
// and if not, we give undefined so that value will be asked again from the user
return askXY(
!isNaN(x_) ? x_ : undefined,
!isNaN(y_) ? y_ : undefined
);
}
// success!
alert(x_ + " + " + y_ + " = " + (x_ + y_));
}
askXY();
See my JSFiddle example.
The isNaN() is a JavaScript function. It returns true if the given value is not a number (NaN).
var a = isNaN('127') ; // Returns false
var a = isNaN('1273 ') ; // Returns false
var b = isNaN(-1.23) ; // Returns false
var c = isNaN(5-2); // Returns false
var d = isNaN(0) ; // Returns false
var e = isNaN("Hell o") ; // Returns true
var f = isNaN("2005/12/12"); // Returns true
Try this:
$(document).ready(function() {
var x = parseInt(prompt("Please enter the first number!"));
var y = parseInt(prompt("Please enter the second number!"));
function add(x, y) {
var z = x + y;
var i = false;
do {
if (isNaN(x)) {
alert("Invalid entry for first number. Please enter a number!");
x = parseInt(prompt("Please enter first number again!"));
} else if (isNaN(y)) {
alert("Invalid entry for second one. Please enter a number!");
y = parseInt(prompt("Please enter Second number again!"));
} else {
z = x + y;
alert(x + " + " + y + " = " + z);
i = true;
}
}while (i == false);
}
add(x, y);
});
This is a compiled demo version. Checkout the Fiddle:
Fiddle

Categories

Resources