Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

jquery - Javascript credit card field - Add space every four chars - Backspace not working properly

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.

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

Updated JS Fiddle: https://jsfiddle.net/ot2t9zr4/10/

Snippet

$('#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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Bind keypress event only and see.

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

Check here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...