在keypress javascript上调用Enter事件

时间:2018-06-18 11:15:27

标签: javascript jquery html

我有以下代码验证最多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'的想法?

2 个答案:

答案 0 :(得分:1)

检查键码13并提交表格:

if (evt.keyCode == '13') {
  document.querySelector('#welcome_submit').click();
}

&#13;
&#13;
$('#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();
    }
    if (evt.keyCode == '13') {
      document.querySelector('#welcome_submit').click();
    }
  });
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

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