Do this:
<html>
<head>
<meta charset='utf-8'/>
<title></title>
</head>
<body>
<p>
<input type="text" id='name'/>
</p>
<input type="button" name="botão" id="verificarvalor" value="Verificar">
<p id="mensagem"></p>
</div>
<script type="text/javascript" >
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1;
}
// campos texto e botao
var el = document.getElementById('name'), btn = document.getElementById('verificarvalor');
// esperar click sobre o botao
btn.addEventListener('click', function(e){
e.preventDefault();
// verificar se o valor digitado é um numero
if(!isNaN(el.value)){
if(isPrime(el.value)){
alert(el.value + ' é primo');
} else {
alert(el.value + ' nao é primo');
}
} else {
return false;
}
});
</script>
</body>
</html>
function isPrime(num) {
for(var i = 2; i < num; i++)
if(num % i === 0) return false;
return num !== 1;
}
// campos texto e botao
var el = document.getElementById('name'), btn = document.getElementById('verificarvalor');
// esperar click sobre o botao
btn.addEventListener('click', function(e){
e.preventDefault();
// verificar se o valor digitado é um numero
if(el.value && !isNaN(el.value)){
if(isPrime(el.value)){
alert(el.value + ' é primo');
} else {
alert(el.value + ' nao é primo');
}
} else {
return false;
}
});
<html>
<head>
<meta charset='utf-8'/>
<title></title>
</head>
<body>
<p>
<input type="text" id='name'/>
</p>
<input type="button" name="botão" id="verificarvalor" value="Verificar">
<p id="mensagem"></p>
</div>
</body>
</html>
In any programming language (at least I know of) no code after return
is executed. Also, in your code the assignments were poorly made, declaring primo(num)
to the button would be invalid, because there is no longer any num in the given context, and the button has no value. Another thing is the placement of the script
tag, it is always preferable to place it just after the set that will execute it, usually next to the tag </body>
.
Alternatively, if you want something much simpler, you can do this:
<input type="text" id='name'/>
</p>
<input type="button" name="botão" id="verificarvalor" value="Verificar" onclick="primo()">
<p id="mensagem"></p>
</div>
And the javascript code:
function primo(){
var el = document.getElementById('name'), msg = document.getElementById('mensagem');
if(el.value && !isNaN(el.value)){
if((el.value % 2) === 1){
msg.innerHTML = "Numero: " + el.value + " e primo";
} else {
msg.innerHTML = "Numero: " + el.value + " nao e primo";
}
}
}
If you prefer something even simpler, the solution is to replace this expression inside the if:
(el.value % 2) === 1
For this one:
el.value & 1
SOpt - Function to check if number is prime in Javascript