 Lo Ri -4 years ago 54
HTML Question

# javascript specific alert when textbox is empty in maximum of 3 numbers algorithm

I'm new to coding and trying to solve an algorithm using javascript. I have to find the maximum out of 3 numbers input in 3 textboxes and alert it. I have done that but I still have to alert some messages when textboxes are left empty, without inputs.
So when all 3 fields remain empty I have to generate a specific alert message and although I wrote something, I always get: "NaN" alert. Instead of NaN I want to get: "Introduceti cel putin un numar". Can you help me with this?
Here is my code (html and javascript).

Thanks!

``````<!doctype HTML>
<html>

<head>
<title>Algoritmi</title>
<script src="point2.js">

</script>
</head>

<body>
<form name="mainForm" style="text-align:center">
<input type="text" name="textBox1" /> <br/>
<input type="text" name="textBox2" /> <br/>
<input type="text" name="textBox3" /> <br/>
<input type="button" value="Afiseaza maxim" onclick=" javascript: calcMax()" />
</form>
</body>

</html>
``````

And Javascript:

``````function calcMax() {
var a = parseInt(document.mainForm.textBox1.value);
var b = parseInt(document.mainForm.textBox2.value);
var c = parseInt(document.mainForm.textBox3.value);
var max;
if (a == null || a == "" && b == null || b == "" && c == null || c == "") {
alert("Introduceti cel putin un numar");
}
else {
if (a > b) {
if (a > c) {
max = a
}
else {
max = c;
}
}
else {
if (b > c) {
max = b
}
else {
max = c;
}
}
alert(max);
}
}
`````` ibrahim mahrir
Answer Source

Note 1: `&&` has higher precedence than `||`, you should wrap `||` test in parenthesis.

Note 2: You can just check the `length` of tha values to check if they are empty or not.

Note 3: To calculate the max of the three value, you can simply use `Math.max`.

``````function calcMax() {
// no need for parseInt
var a = document.mainForm.textBox1.value;               // you can add .trim() at the end to remove surrounding spaces
var b = document.mainForm.textBox2.value;               // ...
var c = document.mainForm.textBox3.value;               // ...
var max;

if (a.length * b.length * c.length === 0) {             // at least one of the inputs value's length is 0
alert("You must fill the inputs");
}
else if(isNaN(a) || isNaN(b) || isNaN(c)) {             // at least one of the inputs value is not a valid number
alert("inputs must be filled with numbers");
}
else {
max = Math.max(a, b, c);                            // a, b and c are all numbers, use Math.max to calculate the maximum (at this stage a, b and c are string, Math.max will internally convert them to numbers)
alert(max);
}
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added