Home Web Front-end JS Tutorial js formatting amount and bank card number in the input box_javascript skills

js formatting amount and bank card number in the input box_javascript skills

May 16, 2016 pm 03:17 PM

我们在项目中经常遇到需要格式化的金额数和银行卡号,一般我们常见的有两种表现形式:输入框内格式化和输入框外格式化。这里我主要把我在项目中遇到的输入框内部格式化的,代码亮出来,框外的格式化相对简单一点。

页面代码:

<div class="wrap">
  <input type="text" id="bankCard" placeholder="输入银行卡号">
</div>
 
<div class="wrap">
  <input type="text" id="moneyNum" placeholder="输入金额">
</div>
Copy after login

银行卡号格式化

//卡号每4位一组格式化
    $("#bankCard").on("keyup", formatBC);
 
    function formatBC(e){
 
      $(this).attr("data-oral", $(this).val().replace(/\ +/g,""));
      //$("#bankCard").attr("data-oral")获取未格式化的卡号
 
      var self = $.trim(e.target.value);
      var temp = this.value.replace(/\D/g, '').replace(/(....)(&#63;=.)/g, '$1 ');
      if(self.length > 22){
        this.value = self.substr(0, 22);
        return this.value;
      }
      if(temp != this.value){
        this.value = temp;
      }
    }
 
Copy after login

这里用“keyup”事件处理格式化,每4位数一组中间空格隔开。但是数据格式化以后又不利于计算,所以给当前元素添加一个属性“data-oral”,保存未处理的数字,这样计算或者要传递到后台可以获取“data-oral”的值。

金额格式化
金额格式化和银行卡号格式化类似,但又有点不同,因为金额每3位数一组用逗号隔开,一般最后有小数点且保留两位有效数字。这里我开始用到“keyup”和"change"事件,但是IE浏览器对于change事件存在兼容问题,可以改用focus和blur事件代替

类似给元素添加属性“data-oral”保存未格式化的数字。

/*
    * 金额每3位数一组逗号隔开格式化
    * 1.先把非数字的都替换掉
    * 2.由于IE浏览器对于change事件存在兼容问题,改用focus和blur事件代替。
    * */
    $("#moneyNum").on("keyup", formatMN);
 
    $("#moneyNum").on({
      focus: function(){
        $(this).attr("data-fmt",$(this).val()); //将当前值存入自定义属性
      },
      blur: function(){
        var oldVal=$(this).attr("data-fmt"); //获取原值
        var newVal=$(this).val(); //获取当前值
        if (oldVal!=newVal) {
          if(newVal == "" || isNaN(newVal)){
            this.value = "";
            return this.value;
          }
          var s = this.value;
          var temp;
 
          if(/.+(\..*\.|\-).*/.test(s)){
            return;
          }
          s = parseFloat((s + "").replace(/[^\d\.\-]/g, "")).toFixed(2) + "";
          var l = s.split(".")[0].split("").reverse(),
              r = s.split(".")[1];
          t = "";
          for(i = 0; i < l.length; i ++ ) {
            t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length && (l[i+1]!='-')&#63; "," : "");
          }
          temp = t.split("").reverse().join("") + "." + r;
          this.value = temp;
          return this.value;
        }
      }
    });
 
    function formatMN(e){
      this.value = this.value.replace(/[^\d\.\-]/g,"");
      $(this).attr("data-oral", parseFloat(e.target.value.replace(/[^\d\.-]/g, "")));
      //$("#moneyNum").attr("data-oral")获取未格式化的金额
    }
Copy after login

其实我觉得,输入框外的格式化更合理一些,大多数都是输入框外部格式化的,我写了个例子也拉出来吧。

输入框外部格式化卡号
原理很简单,就是隐藏一个显示格式化的模块,当输入框获取焦点时显示,失去焦点时隐藏即可。

页面代码:

<div class="inputCard-wrap">
  <input type="text" class="inputCard">
  <div class="panelCard"></div>
</div>
 
<style type="text/css">
  .inputCard-wrap{
    position: relative;
  }
  .inputCard-wrap .panelCard{
    display: none;
    position: absolute;
    top:-34px;
    left:0;
    z-index: 100;
    background-color:#fff9da;
    border:1px #ffce6e solid;
    padding:10px;
    height:40px;
    font-size: 1.7em;
    line-height:18px;
    color:#585858;
  }
</style>
Copy after login

格式化代码:

/* 银行卡号实时验证放大显示 */
$(".inputCard").keyup(function(e){
  var self = $.trim(e.target.value),
    parent = $(e.target).closest(".inputCard-wrap"),
    panel = $(".panelCard", parent),
    val = self.replace(/\D/g, '');
  if(self.length > 18){
    this.value = self.substr(0, 18);
    return this.value;
  }
  if(val == self){
    panel.show();
    val = self.replace(/(....)(&#63;=.)/g, '$1 ');
    panel.html(val);
  }else{
    panel.hide();
    return self;
  }
});
$(".inputCard").unbind('focusin');
$(".inputCard").bind('focusin',function(e){
  var self = $.trim(e.target.value),
    parent = $(e.target).closest(".inputCard-wrap"),
    panel = $(".panelCard", parent),
    val = self.replace(/(....)(&#63;=.)/g, '$1 ');
  if(val != '') {
    panel.show();
    panel.html(val);
  }
});
$(".inputCard").unbind('focusout');
$(".inputCard").bind('focusout',function(e){
  var parent = $(e.target).closest(".inputCard-wrap"),
    panel = $(".panelCard", parent);
  panel.hide();
});
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助。

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles