Home > php教程 > PHP开发 > Implementation code based on jquery to automatically insert spaces into every 4 digits of bank card numbers

Implementation code based on jquery to automatically insert spaces into every 4 digits of bank card numbers

高洛峰
Release: 2016-12-05 16:45:24
Original
1576 people have browsed it

难点不是插入空格,而是修正光标的位置,这个只支持IE9+、chrome浏览器

注意:这个使用了jquery框架

核心代码

$(function() {
 
      $('#kahao').on('keyup', function(e) {
       //只对输入数字时进行处理
        if((e.which >= 48 && e.which <= 57) ||
            (e.which >= 96 && e.which <= 105 )){
          //获取当前光标的位置
          var caret = this.selectionStart
          //获取当前的value
          var value = this.value
          //从左边沿到坐标之间的空格数
          var sp = (value.slice(0, caret).match(/\s/g) || []).length
          //去掉所有空格
          var nospace = value.replace(/\s/g, &#39;&#39;)
          //重新插入空格
          var curVal = this.value = nospace.replace(/(\d{4})/g, "$1 ").trim()
          //从左边沿到原坐标之间的空格数
          var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length
         //修正光标位置
         this.selectionEnd = this.selectionStart = caret + curSp - sp
         
        }
      })
    })
Copy after login

完整代码:已经测试



 

  
  银行卡号4位空格
  

<script> $(function() { $(&amp;#39;#kahao&amp;#39;).on(&amp;#39;keyup&amp;#39;, function(e) { //只对输入数字时进行处理 if((e.which &gt;= 48 &amp;&amp; e.which &lt;= 57) || (e.which &gt;= 96 &amp;&amp; e.which &lt;= 105 )){ //获取当前光标的位置 var caret = this.selectionStart //获取当前的value var value = this.value //从左边沿到坐标之间的空格数 var sp = (value.slice(0, caret).match(/\s/g) || []).length //去掉所有空格 var nospace = value.replace(/\s/g, &amp;#39;&amp;#39;) //重新插入空格 var curVal = this.value = nospace.replace(/(\d{4})/g, &quot;$1 &quot;).trim() //从左边沿到原坐标之间的空格数 var curSp = (curVal.slice(0, caret).match(/\s/g) || []).length //修正光标位置 this.selectionEnd = this.selectionStart = caret + curSp - sp } }) }) </script>
Copy after login

经过测试确实很好用,里面用到了很多的正则

\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template