键入时如何格式化TextBox?

时间:2016-08-02 17:20:28

标签: javascript c# asp.net

当用户输入文本框时,我希望它用小数字格式化自己。

例如,如果用户键入10000,我希望它在键入时显示为10,000

5 个答案:

答案 0 :(得分:1)

你走了。处理退格/删除使其特别具有挑战性。那很有趣! : - )

我已将此添加到我rack.pub的在线脚本组合中。



function toast(a,b){b||(b=2750);var c={message:a,timeout:b};snackbarContainer.MaterialSnackbar.showSnackbar(c)}var doc=document,textArea=doc.getElementById("area"),numArray=[],backArray=[],num="",numF="",regx="",thisChar="",lastChar="",str="",index=0;window.snackbarContainer=doc.querySelector("#toast"),textArea.addEventListener("keydown",function(){var a=event.keyCode;if(str=this.value,(8==a||46==a)&&(backArray=[],index=str.length-1,lastChar=str.charAt(index),!isNaN(lastChar)||","==lastChar))for(var b=str.length-1;b>=0;b--){if(" "==str.charAt(b))return;if(isNaN(str.charAt(b))&&","!=str.charAt(b))return;backArray.push(str.charAt(b))}if(32==a&&backArray[1]){var c=backArray.reverse().slice(0,-1).join(""),d=c.replace(/\,/g,""),e=Number(d).toLocaleString().toString(),f=str.lastIndexOf(c);f>=0&&f+c.length>=str.length&&(str=str.substring(0,f)+e),this.value=str}}),textArea.addEventListener("keypress",function(){if(thisChar=this.value.slice(-1),isNaN(thisChar)){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);this.value=a}else{if(" "==thisChar){num=numArray.join(""),numArray=[],numF=Number(num).toLocaleString().toString(),regx=num+"(?!.*"+num+")",regx=new RegExp(regx);var a=this.value.replace(regx,numF);return void(this.value=a)}numArray.push(thisChar)}});

        html body {
            font-family: 'Roboto', sans-serif;
            background: #f5f5f5;
        }
        .text-right{
            text-align:right;
        }
        .text-center{
            text-align:center;
        }
        .text-left{
            text-align:left;
        }
        .thin{
            font-weight: 100;
        }
        .heading{
            font-size:3em;
        }
        .subtitle{
            margin-top: -16px;
        }
        #submit{
            margin-top:10px;
        }

    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.2.0/material.indigo-pink.min.css">
    <link href="https://fonts.googleapis.com/css?family=Roboto:100,400" rel="stylesheet">

    <div class="demo-layout-transparent mdl-layout mdl-js-layout">
        <main class="mdl-layout__content page-content">
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-cell mdl-cell--4-col">
                    <h1 class="mdl-color-text--indigo-900 text-right thin">commas.js demo</h1>
                    <h6 class="mdl-color-text--indigo-500 text-right subtitle">
                        JavaScript to automatically add commas to numbers in a text area
                    </h6>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-cell mdl-cell--4-col">
                    <h6 class="mdl-color-text--black thin">
                        Basically it auto formats numbers as you type in the text area.  Give it a try.
                    </h6>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
            <section class="mdl-grid">
                <div class="mdl-layout-spacer"></div>
                <div class="mdl-textfield mdl-js-textfield mdl-cell mdl-cell--4-col">
                    <textarea class="mdl-textfield__input" type="text" rows= "3" id="area" ></textarea>
                    <label class="mdl-textfield__label" for="area">Type Here...</label>
                </div>
                <div class="mdl-layout-spacer"></div>
            </section>
            
        </main>
    </div>
        
    <!-- IE Compatibility shims DO NOT DELETE-->
      <!--[if lt IE 9]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js""></script>
      <![endif]-->

      <!--[if IE]>
        <script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/4.1.7/es5-shim.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/classlist/2014.01.31/classList.min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/selectivizr/1.0.2/selectivizr-min.js"></script>
        <script src="//cdnjs.cloudflare.com/ajax/libs/flexie/1.0.3/flexie.min.js"></script>
        <link href="../assets/ie.css" rel="stylesheet">
      <![endif]-->
    <!-- end shims -->
    <script defer src="https://code.getmdl.io/1.2.0/material.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用replace和一个正则表达式,然后将其添加到keyup上。

$(selector).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//will replace with commas

答案 2 :(得分:0)

事实证明这个问题比我预期的更具挑战性(我应该知道的更好)。这是我得到的,使用vanilla Javascript。

您可以为TextBox的onkeyup事件设置事件处理程序:

<asp:TextBox ID="txtAutoFormat" runat="server" onkeyup="processKeyUp(this, event)" />

这是Javascript代码:

<script type="text/javascript">

    function extractDigits(str) {
        return str.replace(/\D/g, '');
    };

    function findDigitPosition(str, index) {
        var pos = 0;
        for (var i = 0; i < str.length; i++) {
            if (/\d/.test(str[i])) {
                pos += 1;
                if (pos == index) {
                    return i + 1;
                }
            }
        }
    };

    function isCharacterKey(keyCode) {
        // Exclude arrow keys that move the caret
        return !(35 <= keyCode && keyCode <= 40);
    };

    function processKeyUp(txt, e) {
        if (isCharacterKey(e.keyCode)) {
            var value = txt.value;

            // Save the selected text range
            var start = txt.selectionStart;
            var end = txt.selectionEnd;
            var startDigit = extractDigits(value.substring(0, start)).length;
            var endDigit = extractDigits(value.substring(0, end)).length;

            // Insert the thousand separators
            txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

            // Restore the adjusted selected text range 
            txt.setSelectionRange(findDigitPosition(txt.value, startDigit), findDigitPosition(txt.value, endDigit));
        }
    };
</script>


现金:

CMS在Regex using javascript to return just numbers中从字符串中提取数字的解决方案。

Alan Moore在How do I add thousand separators with reg ex?中插入千位分隔符的正则表达式。

注意: Ron Royston使用toLocaleString的想法也非常有趣。它可以提供更通用的解决方案。您可以替换此行processKeyUp

txt.value = extractDigits(value).replace(/(\d{1,3}|\G\d{3})(?=(?:\d{3})+(?!\d))/g, "$1,");

以下内容:

txt.value = Number(extractNumber(value)).toLocaleString();

答案 3 :(得分:-1)

尝试输入掩码,这是一个例子: http://digitalbush.com/projects/masked-input-plugin/

答案 4 :(得分:-1)

您可以使用jquery masking framework

的引用:

Jquery Masking

Source at git