简体   繁体   中英

How to show an alert in JavaScript based on specific user input

I need an alert that says "enter a digit from 0 to 9 please" when typing a letter, a comma, minus, plus, bracket, question mark etc. (only numbers can be entered).

My alert is not working, I cannot connect it.
I am asking you for help.

The alert should be shown after trying to enter letters, commas etc. in the table, except for numbers

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script> <meta charset="utf-8"> </head> <body> <script type="text/javascript"> (function($) { $.fn.average = function() { var sum = 0; this.each(function() { sum += parseFloat($(this).val()); //; }); return sum / $(this).length; } })(jQuery); $(document).ready(function() { $(":reset") }); $(document).ready(function() { $("#calc").click(function() { var s = $("input[type='number']").average(); console.debug(s); $('#result').html(s); }); $(".reset").on('click', function() { $("#result").html(" "); }) }); </script> <h1>Oblicz średnią:</h1> <form action=""> <input onkeypress="if((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode != 44))return false" type="number"><br> <input onkeypress="if((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode != 44))return false" type="number"><br> <input onkeypress="if((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode != 44))return false" type="number"><br> <div id="result" type="reset"></div><br> <input type="button" id="calc" value="Licz"> <input type="reset" value="Reset" class="reset"> </form> <script> function setTimeout(function() {}, 10); () { confirm("Press a button!"); } </script> </body> </html> 

Using Input type="number" with pattern="[0-9]*" allows letters in firefox as a reference.

So with the help of regex you can prevent different input types. So on your onkeypress method use the following function:

<input onkeypress="preventNonNumericalInput(event)" type="number">

Then declare this function in your js file:

function preventNonNumericalInput(e) {
  e = e || window.event;
  var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
  var charStr = String.fromCharCode(charCode);

  if (!charStr.match(/^[0-9]+$/)){
    alert("Enter a digit from 0 to 9 please")
    e.preventDefault();
  }
}

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