Clarissa M.
asked 02/21/21NEED HELP ASAP JAVA CODE
In Javascript, how do I validate that the marks (Mark 1, Mark 2, and Mark 3) are numbers and not string? If the user enters a string then how do I display an error in result id that, "You cannot enter string, please refresh the page again".
The result id is this: <p id = "result"></p>
I have a function called printResult(){
Here's my code:
function printResult(){
var isValid =true;
//// validates the marks are numbers
var temp = document.getElementById("m1").value;
if(temp == ""){
document.getElementById("result").innerHTML="You cannot enter string, please refresh the page again";
isValid=false;
}
else
document.getElementById("result").innerHTML=;
var temp = document.getElementById("m2").value;
if(temp == ""){
document.getElementById("result").innerHTML="You cannot enter string, please refresh the page again";
isValid=false;
}
else
document.getElementById("result").innerHTML=;
var temp = document.getElementById("m3").value;
if(temp == ""){
document.getElementById("result").innerHTML="You cannot enter string, please refresh the page again";
isValid=false;
}
else
document.getElementById("result").innerHTML=;
Please tell me if this is correct or not?
1 Expert Answer

Patrick B. answered 02/21/21
Math and computer tutor/teacher
<!DOCTYPE HTML>
<HTML>
<label> 1st Mark </label> <input type="text" id="txtNum1"/><br>
<label> 2nd Mark </label> <input type="text" id="txtNum2"/><br>
<label> 3rd Mark </label> <input type="text" id="txtNum3"/><br>
<button type="button" onclick="CalcAvg()"> Calculate Average </button>
<script>
function CalcAvg()
{
alert("CalcAvg");
var iNumbuff1 = document.getElementById("txtNum1").value;
var iNumbuff2 = document.getElementById("txtNum2").value;
var iNumbuff3 = document.getElementById("txtNum3").value;
var regex=/^[0-9]+$/;
if (!iNumbuff1.match(regex)) { alert("Invalid input for num1"); return; }
if (!iNumbuff2.match(regex)) { alert("Invalid input for num2"); return; }
if (!iNumbuff3.match(regex)) { alert("Invalid input for num3"); return; }
var iNum1 = parseInt(iNumbuff1)
var iNum2 = parseInt(iNumbuff2)
var iNum3 = parseInt(iNumbuff3)
if (isNaN(iNum1))
{
alert('invalid data for num1 ');
}
else
{
alert('1st # is valid');
if (isNaN(iNum2))
{
alert('invalid data for num2');
}
else
{
alert(' 2nd # is valid');
if (isNaN(iNum3))
{
alert('invalid data for num3');
}
else
{
var avg = (iNum1+iNum2+iNum3)*1.000/3;
alert(" average is " + avg );
if (avg>=90) { alert("AWESOME!"); }
else if (avg>=80) { alert(" Very Good"); }
else if (avg>=50) { alert(" ok "); }
else { alert("FAIL"); }
}
}
}
}
</script>
</HTML>
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Clarissa M.
Both HTML and JAVA code02/21/21