Currency formatting and calculate data from input box with jquery

1.2k views Asked by At

i'm trying to mix/ create a currency formatting and calculate data from input box. The problem is when i insert number into SELL form: 1000 and qty: 2, the result is 2, it should be 2000 and with the currency format it should be 2.000. I already succeed with only create individually the currency formatting and calculation.

My code:

Form:

<div class="row">
  <div class="col-lg-6"><b>Sell (pcs)</b>
    <input class="form-control" name="h_jual" type="text" id="a" size="30"  onkeyup="count();" onkeydown="return numbersonly(this, event);"/>
  </div>
  <div class="col-lg-6"><b>Qty</b>
    <input class="form-control" name="qty" type="text" id="b" size="30"  onkeyup="count();"/>
  </div>
  <div class="col-lg-6"><b>Total</b>
    <input class="form-control" name="total" type="text" id="c" size="30" onkeyup="count();" readonly/>
  </div>
</div>

Calculation script:

<script type="text/javascript">
function count() {
  var a = $("#a").val();
  var b = $("#b").val();
  c = a * b; 
  $("#c").val(c);
}
</script>

Currency formatting script:

    function titik() {
      var angka = bersihPemisah(bersihPemisah(bersihPemisah(bersihPemisah(document.getElementById('harga').value)))); //input ke dalam angka tanpa titik
      if (document.getElementById('harga').value == "") {
      alert("Jangan Dikosongi");
      document.getElementById('harga').focus();
      return false;
      }
      else
      if (angka >= 1) {
      alert("angka aslinya : "+angka);
      document.getElementById('harga').focus();
      document.getElementById('harga').value = tandaPemisahTitik(angka);
      return false;
      }
    }

    function tandaPemisahTitik(b){
        var _minus = false;
        if (b<0) _minus = true;
        b = b.toString();
        b=b.replace(".","");
        b=b.replace("-","");
        c = "";
        panjang = b.length;
        j = 0;
        for (i = panjang; i > 0; i--){
             j = j + 1;
             if (((j % 3) == 1) && (j != 1)){
               c = b.substr(i-1,1) + "." + c;
             } else {
               c = b.substr(i-1,1) + c;
             }
        }
        if (_minus) c = "-" + c ;
        return c;
    }

    function numbersonly(ini, e){
        if (e.keyCode>=49){
            if(e.keyCode<=57){
            a = ini.value.toString().replace(".","");
            b = a.replace(/[^\d]/g,"");
            b = (b=="0")?String.fromCharCode(e.keyCode):b + String.fromCharCode(e.keyCode);
            ini.value = tandaPemisahTitik(b);
            return false;
            }
            else if(e.keyCode<=105){
                if(e.keyCode>=96){
                    //e.keycode = e.keycode - 47;
                    a = ini.value.toString().replace(".","");
                    b = a.replace(/[^\d]/g,"");
                    b = (b=="0")?String.fromCharCode(e.keyCode-48):b + String.fromCharCode(e.keyCode-48);
                    ini.value = tandaPemisahTitik(b);
                    //alert(e.keycode);
                    return false;
                    }
                else {return false;}
            }
            else {
                return false; }
        }else if (e.keyCode==48){
            a = ini.value.replace(".","") + String.fromCharCode(e.keyCode);
            b = a.replace(/[^\d]/g,"");
            if (parseFloat(b)!=0){
                ini.value = tandaPemisahTitik(b);
                return false;
            } else {
                return false;
            }
        }else if (e.keyCode==95){
            a = ini.value.replace(".","") + String.fromCharCode(e.keyCode-48);
            b = a.replace(/[^\d]/g,"");
            if (parseFloat(b)!=0){
                ini.value = tandaPemisahTitik(b);
                return false;
            } else {
                return false;
            }
        }else if (e.keyCode==8 || e.keycode==46){
            a = ini.value.replace(".","");
            b = a.replace(/[^\d]/g,"");
            b = b.substr(0,b.length -1);
            if (tandaPemisahTitik(b)!=""){
                ini.value = tandaPemisahTitik(b);
            } else {
                ini.value = "";
            }

            return false;
        } else if (e.keyCode==9){
            return true;
        } else if (e.keyCode==17){
            return true;
        } else {
            //alert (e.keyCode);
            return false;
        }

    }

Any help will so appreciate, thank you

2

There are 2 answers

1
CptArcanium On

Can you provide an error or what is going wrong? You might wan't to parse your input to int i.e. var a = parseInt($("#a").val()); Where do you call the titik() function?

And why do you call onkeyup="count()" at id="c"?

Edit: I've updated the fiddle to take in account the 'dot' in the input. Check this fiddle.

function count() {
  var a = parseFloat($("#a").val().replace(/(\.)|(\,)/g,(m,p1,p2) => p1 ? p1 = "" : p2 = "."));
  var b = parseFloat($("#b").val().replace(/(\.)|(\,)/g,(m,p1,p2) => p1 ? p1 = "" : p2 = "."));
  c = a * b; 
  if (!isNaN(c)) {
    $("#c").val(c);
  }
}

**Old fiddle fiddle. and old code:

function count() {
  var a = parseInt($("#a").val());
  var b = parseInt($("#b").val());
  c = a * b; 
  if (!isNaN(c)) {
    $("#c").val(c);
  }
}
0
Kim Steinhaug On

Undoubtedly there are many ways of handling this since we cant even agree on how to express a numbers decimals - do we use a dot or a comma? Unless there are some magic bullet I didnt find in my search fuzzy logic seems to be the best way to go:

Main objective is to detect the delimiter:

  1. Check if both comma and dot exists as this should mean that the decimal pointer is the one used last - parse the numer.
  2. Detect your format, that is are you a comma or dot user. This should be treated as the preferred and main assumption for your fuzzy logic. That is, do you write 100 as 100,00 or 100.00
  3. Try decoding the user input into numbers with the assumption from 1.
  4. Looking at the number in reverse, if the last two digits are followed by a comma or decimal assume this as the delimiter and parse.

Hopefully there is no number 5, or it could be asserting certain criteria for your number so that you could do some calculations and see that this cannot be right and promt the user to verify the numbers before posting.

Also it could be a good idea to use the placeholder for the fields that needs the numbers to contain sample numbers so that the user sees what delimiter to use.

If you have a international website with numbers being entered from all over maby you could use geoip to locate the position of your user. This can be used to preselect the most likely delimiter - like in scandinavia we use comma as delimiter and in america they use dot.

Seems to me that there is not a clear sollution here unless you know from where your numbers are coming from - and the internet means you have no clue.