Javascript信用卡字段-每四个字符增加一个空格-退格键无法正常工作 [英] Javascript credit card field - Add space every four chars - Backspace not working properly

查看:107
本文介绍了Javascript信用卡字段-每四个字符增加一个空格-退格键无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在用户输入其信用卡号时处理的信用卡字段. 假设用户可以输入数字和字母字符,并且必须每四个字符添加一个空格. 输入部分工作正常,但是我在退格上遇到了问题.如果我将光标放在数字上,则可以使用退格键删除,但是当光标位于空格上时,则无法正常工作:在这种情况下,用户必须按住退格键才能正确删除某些输入.

I have a credit card field that I want to handle while the user inputs its credit card number. Assumptions are that the user can enter digits and alphabetic characters, and a space must be added every four characters. The input part works fine, but I have problems with backspace. Deleting with the backspace key works if I the cursor is on a digits, but it does not work fine when the cursor is on a space: in this case the user must hold backspace to properly delete some input.

另一个要求是让剪贴板操作(复制,剪切,粘贴)在该字段上正常工作.

An additional requirement is to let clipboard actions (copy, cut, paste) work properly on that field.

我不能为解决方案使用任何插件(例如JQuery Mask插件),并且如果可能的话,我不会直接使用keyCode.

I cannot use any plugin for the solution (like the JQuery Mask Plugin), and I won't use keyCode directly, if possible.

已更新 JS小提琴: https://jsfiddle.net/ot2t9zr4/10/

代码段

$('#credit-card').on('keypress change blur', function () {
  $(this).val(function (index, value) {
    return value.replace(/[^a-z0-9]+/gi, '').replace(/(.{4})/g, '$1 ');
  });
});

$('#credit-card').on('copy cut paste', function () {
  setTimeout(function () {
    $('#credit-card').trigger("change");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <form class="" action="" method="post">
    <fieldset>
      <legend>Payment</legend>
      <div class="beautiful-field field-group credit-cart">
        <label class="label" for="credit-card">Credit card</label>
        <input class="field" id="credit-card" value="" autocomplete="off" type="text" />
      </div>
    </fieldset>
  </form>
</div>

推荐答案

仅绑定keypress事件并查看.

$('#credit-card').on('keypress change', function () {
  $(this).val(function (index, value) {
    return value.replace(/\W/gi, '').replace(/(.{4})/g, '$1 ');
  });
});

此处中进行检查.

这篇关于Javascript信用卡字段-每四个字符增加一个空格-退格键无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆