Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

javascript - How to check if the value in a text box is prime or not with jQuery

I am trying to determine whether the value in a text box is prime or not using jQuery.

Here is what I've tried so far, but it's not working:

$("#textbx").keyup(function(){
 if ($("#textbx").val().length > 0) {
  $("#btn").removeAttr('disabled');
 
   }
});

 $("#textbx").blur(function(){
    if ($("#textbx").val().length ==0) {
  $("#btn").attr('disabled','disabled');
 
   }
  });
 
 $("#textbx").keypress(function (e) {
     if (e.which!=8 && (e.which < 48 || e.which > 57)) {
        $("#msg").html("plz press nimber only").show().fadeOut("slow");
               return false;
    }
   });
 
  $("#btn").click(function(){
  
   var num =parseInt($("#textbx").val()); 
   var i;

   for (var i = 2; i >num/2; i++) { 
   
        if(i%num==0)
{ $("#msg").html("yupp").show().fadeOut("slow");
}
else
{$("#msg").html("huh").show().fadeOut("slow");
}
break;
       }
  });
#msg
{
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="textbx" type="text" /><button id="btn" disabled="disabled">go</button>
 <span id="msg"></span>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is your code slightly modified

DEMO http://jsfiddle.net/72FtQ/1/

function isPrime(n) {

   // If n is less than 2 or not an integer then by definition cannot be prime.
   if (n < 2) {return false}
   if (n != Math.round(n)) {return false}

   // Now check every whole number from 2 to the square root of n. If any of these divides n exactly, n cannot be prime.
   for (var i = 2; i <= Math.sqrt(n); i++) {
      if (n % i == 0) {return false}
   }

   // If n%i was never == 0 above, then n must be prime
   return true;

}

SOURCE http://studymaths.co.uk/topics/checkIfPrime.php


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...