我可以在插入时间内每4个数字为信用卡号字段添加破折号吗

Nim*_*tel -1 javascript php

帮我在插入时在文本框中输入信用卡号格式1111-1111-1111-1111。

 <div class="form-group">
        <label>Card Number</label>
        <input type="text" class="form-control" placeholder="xxxx-xxxx-xxxx-xxxx" name="card-number" id="credit-card" value="" >
    </div>
    <div class="form-group center-block">
        <input type="button" name="btn-update" id="btn-update" value="UPDATE" class="btn">
 </div>
Run Code Online (Sandbox Code Playgroud)

Tar*_*ngP 7

如果您使用的是jQuery

$('.creditCardText').keyup(function() {
  var foo = $(this).val().split("-").join(""); // remove hyphens
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,4}', 'g')).join("-");
  }
  $(this).val(foo);
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" class="creditCardText" value="1234-1234-1234-1234" />
Run Code Online (Sandbox Code Playgroud)