![](/img/trans.png)
[英]How to create a function using javascript which will check a field value/user input and show alert if the input is correct?
[英]How to show an alert in JavaScript based on specific user input
輸入字母,逗號,減號,加號,方括號,問號等時,我需要顯示“請輸入0到9之間的數字”的警報(只能輸入數字)。
我的警報不起作用,我無法連接它。
我正在尋求您的幫助。
嘗試在表格中輸入字母,逗號等后,應顯示警告,數字除外
<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>
使用輸入type =“ number”和pattern =“ [0-9] *”可以將Firefox中的字母作為參考。
因此,借助regex
您可以防止使用不同的輸入類型。 因此,在您的onkeypress
方法上使用以下功能:
<input onkeypress="preventNonNumericalInput(event)" type="number">
然后在您的js
文件中聲明此函數:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.