I am having difficulty with this script showing the yes or no permanently. Could anyone tell me why?
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Project</title>
</head>
<body>
<h1>Is it prime?</h1>
<hr>
<p>This tool was designed to determine if a number is prime </p>
<form>
<input type="number" id="Number" name="enterednumber"/>
<input type="submit" id="theButton" onclick="isitprime(this.form.enterednumber.value)"/>
</form>
<p id="answer"></p>
</body>
<script>
function isitprime(v)
{
var isprime=0;
for(i=2, i<v, i++)
{
if(v%i==0)
isprime=1;
}
if(isprime==1)
document.getElementById("answer").innerHTML="No";
else
document.getElementById("answer").innerHTML="Yes";
}
</script>
</html>
Basically I am trying to pass an entered value to my function isitprime() and then have text that says yes or no pop up.
The first thing I see is that in your script you are looking for an element with an id
of "maybe"
. But in your html the place you want the output to appear has an id
of "answer"
.
You also don't want to use a body
element inside another body element. Instead just use a div for your answer like this:
<div id="answer"></div>
Also in your for loop use ; instead of ,
for(i=2; i<v; i++)
I suspect another issue you might be seeing is that the form is submitted which means the page gets refreshed after you've set the yes/no value. You might could suppress the form submission by returning false after you call your method (or return false from your method). Like so:
<body>
<h1>Is it prime?</h1>
<hr>
<p>This tool was designed to determine if a number is prime </p>
<form>
<input type="number" id="Number" name="enterednumber"/>
<input type="submit" id="theButton" onclick="return isitprime(this.form.enterednumber.value)"/>
</form>
<p id="answer"></p>
</body>
<script>
function isitprime(v) {
var isprime=0;
for(i=2; i<v; i++) {
if(v%i==0) {
isprime=1;
}
}
if(isprime==1) {
document.getElementById("answer").innerHTML="No";
}
else {
document.getElementById("answer").innerHTML="Yes";
}
return false; // make sure that the form doesn't get submitted
}
</script>
Alternatively, you could run the isitprime
function on page load which could take the value from the query string.
yes you just need to return false after the function like this
<input type="submit" id="theButton" onclick="isitprime(this.form.enterednumber.value);return false;"/>
you have other ways to do it with to form action tag you can read about it more
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.