Posted by: piman007 | 29-05-2007

JavaScript รับค่าตัวเลขพร้อมกับใส่จุลภาคและทศนิยม 2 ตำแหน่ง

 
 
         <input name="field5" size=40 value="" style="text-align:right" onKeyUp="chkCurrency(this);" Onblur="convertCurrency(this)">
 
        <script>
         var temp = ”;
         function chkCurrency(obj){
          var key=event.keyCode;
  
          // 44, 188 is ascii code of ‘,’          
          // 46 , 190 is ascii code of  ‘.’
          // 37 is ascii code of  arrow left
          // 39 is ascii code of arrow right
          //  8 is ascii code of  backspace
          // 13 is ascii code of enter
          if((key>=48&&key<=57)  || (key==44) || (key==188)  || (key==46) || (key==13) || (key==8) || (key==190) || (key==37) || (key==39)){
           temp = obj.value;
          }else{
           alert(‘Only Number!!! ‘+key);
           obj.value=temp;
          }
          return false;
         }
         function convertCurrency(obj){
           var temp = ”;
           var strValue = obj.value;
           if(strValue=="") strValue = "";
           strValue = strValue.replace(/,/g,"");
           var num = parseFloat(strValue);
           var result = num .toFixed(2);
           obj.value = addCommas(result.toString());
         }
         function addCommas(nStr)
         {
          nStr += ”;
          x = nStr.split(‘.’);
          x1 = x[0];
          x2 = x.length > 1 ? ‘.’ + x[1] : ”;
          var rgx = /(d+)(d{3})/;
          while (rgx.test(x1)) {
           x1 = x1.replace(rgx, ‘$1’ + ‘,’ + ‘$2’);
          }
          return x1 + x2;
         }
        </script>        
 

ใส่ความเห็น

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / เปลี่ยนแปลง )

Twitter picture

You are commenting using your Twitter account. Log Out / เปลี่ยนแปลง )

Facebook photo

You are commenting using your Facebook account. Log Out / เปลี่ยนแปลง )

Google+ photo

You are commenting using your Google+ account. Log Out / เปลี่ยนแปลง )

Connecting to %s

หมวดหมู่

%d bloggers like this: