简体   繁体   中英

JavaScript id output only displays for a second then dissapears

I am making a simple JavaScript function where you enter two numbers in a form and then the function determines if the sum of the two numbers is a prime. It all works but when the function displays a message with the document.getElementById("demo").innerHTML and

it is only on the web page for one second then disappears. I want to make it so the message stays until you click on the button again. I have searched this site and other site but have not been able to find anything.

Here is the code:

 <!DOCTYPE html> <html> <head> <link href="/prime.css" rel="stylesheet" type="text/css" /> <script> function prime() { // get the values from the form var x= document.forms["frm1"]["x"].value; var y= document.forms["frm1"]["y"].value; //test the values of the form if (x == "null"|| x=="" || isNaN(x)|| y=="null" || y==""|| isNaN(y)){ alert("You must enter two numbers."); exit; } //change variables to number and add them together var number = (parseInt(x)+ parseInt(y)); var a=""; var prime = true; //check to make sure number is not less than one if (number <= 1){ alert("Sorry " +number+ " is not a prime."); prime = false; exit; } //check if number is a prime for (var dividby = 2; dividby <= number / 2; dividby++){ if(number % dividby == 0) prime = false; break; } //send congratulations if(prime==true){ a="congratulations " + number + " is a prime!"; } //send condolences else{ a="Sorry "+number+ " is not a prime."; } document.getElementById("demo").innerHTML=a; } </script> </head> <body id="elem"> <div class="div"></div> <div> <br> <h1>PRIME NUMBERS</h1> <p>Please enter two numbers to be added and see if the result is a prime.</p><br> <form name="frm1" > <input type="text" name="x"> + <input type="text" name="y"> <button onclick="prime()">click me</button> </form> <br> <p id="demo"></p> </div> </body> </html> 

The problem is that your "click me" button is actually submitting the form, causing the page to reload (since your <form> doesn't have an action attribute, it submits to the same page). The <button> tag defaults to type="submit" . To make it NOT a submit button, you need to change it like this:

<button onclick="prime()" type="button">click me</button>

I just tried the code, and what happens is simple: your form is posted when you click the button.

In the button onClick, write onClick=" return prime();" and add a

return false;

in your javascript function.

In your form tag, just add onsubmit="return false;" like this-

<form name="frm1" onsubmit="return false;" >

This will prevent your form from being submitted.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM