2016-08-02 78 views
1

當用戶輸入文本框時,我希望它用小數格式化自己。如何在輸入時格式化TextBox?

例如,如果用戶鍵入10000,我希望它在顯示類型時顯示爲10,000

+2

你要做到這一點在JavaScript的** **,_not_在C#代碼(我更新了標籤您)。 –

+0

嗯謝謝,有什麼想法該怎麼做? –

+0

如果你是ASP.Net MVC,那麼你可以在模型中的所需屬性上使用'DisplayFormat'屬性。 – Transcendent

回答

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>

+0

謝謝:)完美作品 –

+0

很高興聽到它。我將不勝感激。只是好奇,爲什麼你不接受我的答案? –

-1

您可以使用jQuery遮蔽框架

引用:

Jquery Masking

Source at git

+0

請不要張貼任何其他鏈接。見[回答]。提供一個特別回答這個問題的例子。 –

0

使用替代和正則表達式然後只是在keyup上排隊。

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

鍵控不起作用(快速打字)。按鍵需要。 –

0

這一問題被證明是比我預期的(我應該知道更好)更具挑戰性。這是我得到的,使用vanilla Javascript。

您可以設置事件處理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(); 
+0

此代碼不起作用。 [Codepen here](http://codepen.io/rhroyston/pen/ALBYPm) –