javascript - Trying to prevent user from entering a non-number or a number above a certain range -


here's have far problem if enter number 16,it won't allow me change what's in text box anymore. looking on how fix that,thanks guys.

 <script language=javascript>   <!--   function isnumberkey(evt)   {      var charcode = (evt.which) ? evt.which : event.keycode      if (charcode > 31 && (charcode < 48 || charcode > 57))         return false;       var num = document.getelementbyid('quantity').value          var y  = parseint( num  ,  10  )           if ( y > 15 )          return false;           return true;      }  </script>   <form action="regservlet" method="post">     <p>         enter quantity purchase  :  <input name="quantity" onkeypress="return isnumberkey(event)" id ="quantity" size=15 type="text" value="1"/>     </p> </form> 

this possible solution, have removed inline event handler in favour of assigning addeventlistener

i have changed using keypress event keyup

i stripping, regex, non-numeric characters regardless, not bothing check pressed.

we parseint value of input element , if number greater specified, slice off last character entered.

html

<p>enter quantity purchase :     <input name="quantity" id="quantity" size=15 type="text" value="1" /> </p> 

javascript

var quantity = document.getelementbyid("quantity");  function verify(evt) {     var target = evt.target;      target.value = target.value.replace(/[^\d]/, "");     if (parseint(target.value, 10) > 15) {         target.value = target.value.slice(0, target.value.length - 1);     } }  quantity.addeventlistener("keyup", verify, false); 

on jsfiddle

wrapping whole thing in window.onload event.

notes

the load event fires @ end of document loading process. @ point, of objects in document in dom, , images , sub-frames have finished loading.

window.addeventlistener("load", function () {     document.getelementbyid("quantity").addeventlistener("keyup", function (evt) {         var target = evt.target;          target.value = target.value.replace(/[^\d]/, "");         if (parseint(target.value, 10) > 15) {             target.value = target.value.slice(0, target.value.length - 1);         }     }, false); }); 

on jsfiddle


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -