首页 > 解决方案 > 在按键 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”的任何想法?

标签: javascriptjqueryhtml

解决方案


您可以在表单上收听提交事件,而不是在输入上收听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>


推荐阅读