Home > Web Front-end > JS Tutorial > body text

js code that limits the input value to floating point for the input box

巴扎黑
Release: 2017-09-26 09:42:21
Original
1475 people have browsed it

The following editor will bring you a js code that limits the input value of the input box to floating point. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

In some projects, for example, the amount uses floating point type. For input restrictions, you can refer to the following


<script>
  function only_num(obj){
    //得到第一个字符是否为负号
    var num = obj.value.charAt(0);
    //先把非数字的都替换掉,除了数字和.
    obj.value = obj.value.replace(/[^\d\.]/g,&#39;&#39;);
    //必须保证第一个为数字而不是.
    obj.value = obj.value.replace(/^\./g,&#39;&#39;);
    //保证只有出现一个.而没有多个.
    obj.value = obj.value.replace(/\.{2,}/g,&#39;.&#39;);
    //保证.只出现一次,而不能出现两次以上
    obj.value = obj.value.replace(&#39;.&#39;,&#39;$#$&#39;).replace(/\./g,&#39;&#39;).replace(&#39;$#$&#39;,&#39;.&#39;);
    //如果第一位是负号,则允许添加
    if(num == &#39;-&#39;){
      obj.value = &#39;-&#39;+obj.value;
    }
  }
</script>
Copy after login

The above is the detailed content of js code that limits the input value to floating point for the input box. For more information, please follow other related articles on the PHP Chinese website!

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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template