Home > Mobile >  Remove comma before form is submitted
Remove comma before form is submitted

Time:08-25

I have a small loan investment calculator. I added a keyup event to insert the comma into the 'investment' field, but now there is an error on submitting the form because the comma cannot be used in the calculation.

How can I edit my code so the calculation can still be processed?

I tried adding a deleteThousandSeparator function to escape the comma before it is submitted, but as you can see this does not work.

$(document).ready(function() {
        $('.project-selector select').change(function() {
            $.ajax({
                url: '/project/get-pattern-list?id='   $(this).val(),
                type: 'get',
                /*dataType: 'json',*/
                success: function(response) {
                    $('.pattern-selector select').html(response);
                    if (response.trim() == "") $('.pattern-selector').hide();
                    else $('.pattern-selector').show();
                    reload_data();
                }
            });
        });
        $('.pattern-selector select').change(function() {
            reload_data();
        });

        function reload_data() {
            $.ajax({
                url: '/project/get-pattern-info?projectid='   $('.project-selector select').val()   "&id="   $('.pattern-selector select').val(),
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    if (response.length > 0) {
                        $('.pattern-name').text(response[0].name);
                        $('.pattern-area').text(response[0].total_area);
                        $('.pattern-price').text(parseInt(response[0].price) );
                    } else {
                        $('.pattern-name').text("-");
                        $('.pattern-area').text("-");
                        $('.pattern-price').text("-");
                    }
                }
            });
        }

    
        function CheckForDigit(checkValue) {
            var valid = true;
            if (isNaN(checkValue))
                valid = false;
            if (checkValue == "")
                valid = false;
            return valid;
        }

        function FormatNumberToString(nStr) {
            //nStr = nStr.toFixed(2);
            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;
        }

        function CalculatePMT(pv, rate, years) {
            return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1   rate / 100 / 12) , ( years * 12))));

        }
       
        /************** CALCULATE 2 *************/
        $("#cal2_btnCalculate").click(Calculate2);

        function Calculate2(event) {
            var years = $("#cal2_txtTenor").val();
            var rate = $("#cal2_txtInterestRate").val();
            var pv = $("#cal2_txtLoan").val();
            if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
                var ir = (rate / 100) * 100; // For LH, add 1 more
                var installment = CalculatePMT(pv, ir, years);
                $("#cal2_txtInstallment").val(FormatNumberToString(installment));
                $("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
            } else
                alert("processing error");
        }
        /*****************************************/
      
    });
    
    


var cal2_txtLoan = document.getElementById('cal2_txtLoan');

cal2_txtLoan.addEventListener('keyup', function() {
  var val = this.value;
  val = val.replace(/[^0-9\.]/g,'');
  
  if(val != "") {
    valArr = val.split('.');
    valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
    val = valArr.join('.');
  }
  
  this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    
<script>
function deleteThousandSeparator(){
  const cal2_txtLoan = document.getElementById('cal2_txtLoan');
  cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
                    <form onsubmit="return deleteThousandSeparator()">


                        <div >
                            <div >
                            </div>
                            <div>
                                <input id="cal2_txtLoan"   type="text" placeholder="amount">
                            </div>
                        </div>
                        <div >

                            <div >
                                <input id="cal2_txtTenor"  type="number" placeholder="1-30 years">
                            </div>
                        </div>
                        <div >
                            <div >
                                <input id="cal2_txtInterestRate"  type="number" placeholder="percent (%)">
                            </div>
                        </div>
                        <div >
                            <div >
                                <div >
                                    <div >
                                        <button type="button" id="cal2_btnCalculate" >submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div >
                            <div >
                                <label >Summary of monthly installments</label> <input id="cal2_txtInstallment"  disabled="disabled" type="text"> <span  style="color:red;">* Result is just a guide</span>
                            </div>
                        </div>
                    </form>
                  

CodePudding user response:

Just with replacing comma , globally with empty space, and convert string to a number with

var pv =  $("#cal2_txtLoan").val().replace(/,/g, '');

$(document).ready(function() {
        $('.project-selector select').change(function() {
            $.ajax({
                url: '/project/get-pattern-list?id='   $(this).val(),
                type: 'get',
                /*dataType: 'json',*/
                success: function(response) {
                    $('.pattern-selector select').html(response);
                    if (response.trim() == "") $('.pattern-selector').hide();
                    else $('.pattern-selector').show();
                    reload_data();
                }
            });
        });
        $('.pattern-selector select').change(function() {
            reload_data();
        });

        function reload_data() {
            $.ajax({
                url: '/project/get-pattern-info?projectid='   $('.project-selector select').val()   "&id="   $('.pattern-selector select').val(),
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    if (response.length > 0) {
                        $('.pattern-name').text(response[0].name);
                        $('.pattern-area').text(response[0].total_area);
                        $('.pattern-price').text(parseInt(response[0].price) );
                    } else {
                        $('.pattern-name').text("-");
                        $('.pattern-area').text("-");
                        $('.pattern-price').text("-");
                    }
                }
            });
        }

    
        function CheckForDigit(checkValue) {
            var valid = true;
            if (isNaN(checkValue))
                valid = false;
            if (checkValue == "")
                valid = false;
            return valid;
        }

        function FormatNumberToString(nStr) {
            //nStr = nStr.toFixed(2);
            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;
        }

        function CalculatePMT(pv, rate, years) {
            return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1   rate / 100 / 12) , ( years * 12))));

        }
       
        /************** CALCULATE 2 *************/
        $("#cal2_btnCalculate").click(Calculate2);

        function Calculate2(event) {
            var years = $("#cal2_txtTenor").val()
            console.log(years)
            var rate = $("#cal2_txtInterestRate").val();
            var pv =  $("#cal2_txtLoan").val().replace(/,/g, '');
            console.log(pv)
            if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
                var ir = (rate / 100) * 100; // For LH, add 1 more
                var installment = CalculatePMT(pv, ir, years);
                $("#cal2_txtInstallment").val(FormatNumberToString(installment));
                $("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
            } else
                alert("processing error");
        }
        /*****************************************/
      
    });
    
    


var cal2_txtLoan = document.getElementById('cal2_txtLoan');

cal2_txtLoan.addEventListener('keyup', function() {
  var val = this.value;
  val = val.replace(/[^0-9\.]/g,'');
  
  if(val != "") {
    valArr = val.split('.');
    valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
    val = valArr.join('.');
  }
  
  this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    
<script>
function deleteThousandSeparator(){
  const cal2_txtLoan = document.getElementById('cal2_txtLoan');
  cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
                    <form onsubmit="return deleteThousandSeparator()">


                        <div >
                            <div >
                            </div>
                            <div>
                                <input id="cal2_txtLoan"   type="text" placeholder="amount">
                            </div>
                        </div>
                        <div >

                            <div >
                                <input id="cal2_txtTenor"  type="number" placeholder="1-30 years">
                            </div>
                        </div>
                        <div >
                            <div >
                                <input id="cal2_txtInterestRate"  type="number" placeholder="percent (%)">
                            </div>
                        </div>
                        <div >
                            <div >
                                <div >
                                    <div >
                                        <button type="button" id="cal2_btnCalculate" >submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div >
                            <div >
                                <label >Summary of monthly installments</label> <input id="cal2_txtInstallment"  disabled="disabled" type="text"> <span  style="color:red;">* Result is just a guide</span>
                            </div>
                        </div>
                    </form>

CodePudding user response:

You could format the submitted values first before using them to do your calculation

var years = _formatNumber( $( "#cal2_txtTenor"        ).val() );
var rate  = _formatNumber( $( "#cal2_txtInterestRate" ).val() );
var pv    = _formatNumber( $( "#cal2_txtLoan"         ).val() );

// your calculation logic here

function _formatNumber( str ){
    return str.replace( ',', '' );
}

The working solution below

$(document).ready(function() {
        $('.project-selector select').change(function() {
            $.ajax({
                url: '/project/get-pattern-list?id='   $(this).val(),
                type: 'get',
                /*dataType: 'json',*/
                success: function(response) {
                    $('.pattern-selector select').html(response);
                    if (response.trim() == "") $('.pattern-selector').hide();
                    else $('.pattern-selector').show();
                    reload_data();
                }
            });
        });
        $('.pattern-selector select').change(function() {
            reload_data();
        });

        function reload_data() {
            $.ajax({
                url: '/project/get-pattern-info?projectid='   $('.project-selector select').val()   "&id="   $('.pattern-selector select').val(),
                type: 'get',
                dataType: 'json',
                success: function(response) {
                    if (response.length > 0) {
                        $('.pattern-name').text(response[0].name);
                        $('.pattern-area').text(response[0].total_area);
                        $('.pattern-price').text(parseInt(response[0].price) );
                    } else {
                        $('.pattern-name').text("-");
                        $('.pattern-area').text("-");
                        $('.pattern-price').text("-");
                    }
                }
            });
        }

    
        function CheckForDigit(checkValue) {
            var valid = true;
            if (isNaN(checkValue))
                valid = false;
            if (checkValue == "")
                valid = false;
            return valid;
        }

        function FormatNumberToString(nStr) {
            //nStr = nStr.toFixed(2);
            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;
        }

        function CalculatePMT(pv, rate, years) {
            return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1   rate / 100 / 12) , ( years * 12))));

        }
       
        /************** CALCULATE 2 *************/
        $("#cal2_btnCalculate").click(Calculate2);

        function Calculate2(event) {
            var years = _formatNumber( $( "#cal2_txtTenor"        ).val() );
            var rate  = _formatNumber( $( "#cal2_txtInterestRate" ).val() );
            var pv    = _formatNumber( $( "#cal2_txtLoan"         ).val() );
            if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
                var ir = (rate / 100) * 100; // For LH, add 1 more
                var installment = CalculatePMT(pv, ir, years);
                $("#cal2_txtInstallment").val(FormatNumberToString(installment));
                $("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
            } else
                alert("processing error");
        }
        
        function _formatNumber( str ){
          return str.replace( ',', '' );
        }
        /*****************************************/
      
    });
    
    


var cal2_txtLoan = document.getElementById('cal2_txtLoan');

cal2_txtLoan.addEventListener('keyup', function() {
  var val = this.value;
  val = val.replace(/[^0-9\.]/g,'');
  
  if(val != "") {
    valArr = val.split('.');
    valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
    val = valArr.join('.');
  }
  
  this.value = val;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    
<script>
function deleteThousandSeparator(){
  const cal2_txtLoan = document.getElementById('cal2_txtLoan');
  cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}
</script>
                    <form onsubmit="return deleteThousandSeparator()">


                        <div >
                            <div >
                            </div>
                            <div>
                                <input id="cal2_txtLoan"   type="text" placeholder="amount">
                            </div>
                        </div>
                        <div >

                            <div >
                                <input id="cal2_txtTenor"  type="number" placeholder="1-30 years">
                            </div>
                        </div>
                        <div >
                            <div >
                                <input id="cal2_txtInterestRate"  type="number" placeholder="percent (%)">
                            </div>
                        </div>
                        <div >
                            <div >
                                <div >
                                    <div >
                                        <button type="button" id="cal2_btnCalculate" >submit</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div >
                            <div >
                                <label >Summary of monthly installments</label> <input id="cal2_txtInstallment"  disabled="disabled" type="text"> <span  style="color:red;">* Result is just a guide</span>
                            </div>
                        </div>
                    </form>

CodePudding user response:

You can use replacAll.

replaceAll(",", "")

Basically, you replace the "," with nothing "".

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll

  • Related