Do so:
<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 the ones I know) no code after the return
is executed. Also, in its code the assignments were poorly made, declare primo(num)
for the button, it would be invalid, because for now it does not exist in a in the given context, and the button has no value. Another thing is tag placement script
, it is always preferable to put right after the set that will run it, usually together with the tag </body>
.
Alternatively, if you want something much simpler, you can do it like 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 code javascript:
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
This way:
el.value & 1
Sopt - Function to check if numero is prime in Javascript
Visually you can experiment
onclick=primo(this.value)
and has code after thereturn
.– Edilson
actually a lot is wrong there.
– Edilson
a lot of things, why use
onclick=primo(this.value)
Voce would be taking the value of the boot... and then and areturn
the code is ignored...– LocalHost