javascript - 在按键 javascript 上调用 Enter 事件
问题描述
我有以下代码验证最多 10 位的手机号码,我正在使用输入type="text"
,因为minlength
无法正常工作,type="number"
但问题是当我尝试通过单击键盘输入提交表单时,它没有提交
$('#welcome_submit').on('click', function() {
$.ajax({
url: '/url',
data: $('#entry_form').serialize(),
type: "POST",
datatype: 'JSON',
success: function(data) {
alert('success');
},
error: function(error) {
console.log("Error: error");
},
});
});
$(document).ready(function() {
document.querySelector("input").addEventListener("keypress", function(evt) {
if (evt.which < 48 || evt.which > 57) {
evt.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="entry_form">
<input type="text" value="" placeholder="Enter your Mobile Number" class="form-class" name="phone_no" autocomplete="off" autofocus maxlength="10" />
<button id="welcome_submit" class="btn btn-continue welcome_first" type="submit">Continue</button>
</form>
在上述代码中过滤 Enter 事件“13”的任何想法?
解决方案
您可以在表单上收听提交事件,而不是在输入上收听keyup/keypress事件:
$('#entry_form').on('submit', function(event) {
event.preventDefault();
var serializedData = $(this).serialize();
// Ajax request ...
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="entry_form">
<input type="text" value="" placeholder="Enter your Mobile Number" class="form-class" name="phone_no" autocomplete="off" autofocus maxlength="10" />
<button id="welcome_submit" class="btn btn-continue welcome_first" type="submit">Continue</button>
</form>
推荐阅读
- rx-java - 如何使用带有 EmbeddedChannel 的 rxNetty 客户端进行测试
- php - 使用 Laravel 在服务器上上传图片
- python - 如何从 softmax 层提取权重?
- javascript - 如何在存储在数组中的 html vue js 中提供编辑功能?
- python - 使用 Pandas 计算 Python 中每组列的一些值
- wordpress - Wordpress 单一安装在子目录站点地图重写规则 Nginx
- typescript - 泛型和映射类型缩小
- xml - XSD:独特的元素
- java - 使用 BouncyCastle 接受过期的 CRL
- .net - 缓存从 ASP.NET 核心 Web api 中的大量文件中读取的内容