使用逗号格式化输入字段,并以Div的形式显示为数字格式的值 [英] Format input fields with commas and display in Div as numeric formatted values

查看:104
本文介绍了使用逗号格式化输入字段,并以Div的形式显示为数字格式的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个脚本处理格式化输入的格式(多部分)形式。



我有一个脚本在做数学运算并将总数转换为固定数字总和(感谢 Irvin Dominin链接描述在这里 ElendilTheTall ):

  $(document).ready(function(){
$(function(){
$ (body)。on(blur,#vehiclePrice,#estimatedTaxesAndFees,#downPayment,#manufacturerRebate,#tradeInValue,#amtOwedOnTrade,#extendedWarranty,#gapInsurance,#serviceContract,function(){
updateTotal );
});

var updateTotal = function(){
var input1 = parseInt($('#vehiclePrice')。val())|| 0;
var input2 = parseInt($('#estimatedTaxesAndFees')。val())|| 0;
var input3 = parseInt($('#downPayment')。val())|| 0;
var input4 = parseInt($('#manufacture rRebate')。val())|| 0;
var input5 = parseInt($('#tradeInValue')。val())|| 0;
var input6 = parseInt($('#amtOwedOnTrade')。val())|| 0;
var input7 = parseInt($('#extendedWarranty')。val())|| 0;
var input8 = parseInt($('#gapInsurance')。val())|| 0;
var input9 = parseInt($('#serviceContract')。val())|| 0; (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);

$('。total')。 $('。'total)'。text('$'+ sum.toFixed(2).replace(/(\ d)(?=(\ d {3})+ \。)/ g,'$ 1,'));

var total =(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
};
});
});

我有两个函数处理输入字段并添加一个逗号:

  $(document).ready(function(){
$('input.number')。keyup(function(event){
//跳过箭头键
if(event.which> = 37&& event.which <= 40){
event.preventDefault();
}

var $ this = $(this);
var num = $ this.val()。replace(/,/ gi,).split()。reverse()。 join();
var num2 = RemoveRougeChar(num.replace(/(。{3})/ g,$ 1)。split()。reverse()。join() );

console.log(num2);

//下面一行已被简化,修订历史记录包含原始文件
$ this.val(num2) ;
});
});

函数RemoveRougeChar(convertString){
if(convertString.substring(0,1)==,){
return convertString.substring(1,convertString.length)
}

return convertString;
};

然后是另一个脚本,用于防止在输入字段中去除不需要的字符:

 函数isNumberKey(evt){
var charCode =(evt.which)? evt.which:event.keyCode
$ b $ if(charCode> 31&&(charCode< 48 || charCode> 57))
return false;

返回true;
};

最终我在这里要做的是用逗号格式化输入,不允许任何小数,然后在div中显示一个格式化的值(只有逗号)。一直在防止任何不需要的字符被输入到输入中。



如果我尝试并将所有脚本一起使用,它将只显示输入字段的第一个数字,即逗号前的数字。
$ b

有什么想法?

Das Fiddle

解决方案

目前有三个问题:


  1. 您输入元素的 type =number允许,如果浏览器支持它,您只输入数字,但是您正在追加,因此它会自动清除该值,并将其切换为 type =text

  2. 由于不能以正确的方式执行,请尝试使用 .replace(/,/ gi,'')然后在使用事件而不是 evt
  3. c $ c


    代码:

      $(document).ready(function(){
    $(function(){
    $(body)。on(blur,#vehiclePrice,#estimatedTaxesAndFees,#downPayment,#manufacturerRebate,#tradeInValue,#amtOwedOnTrade,#extendedWarranty,#gapInsurance ,#serviceContract,function(){
    updateTotal();
    });
    var updateTotal = function(){
    var input1 = parseInt($('#vehiclePrice')。val()。replace(/,/ gi,''))|| 0;
    var input2 = parseInt($('#estimatedTaxesAndFees')。val()。replace(/,/ gi,''))|| 0;
    var input3 = parseInt($('#downPayment')。val()。replace(/,/ gi,''))|| 0;
    var input4 = parseInt($('#makerRebate')。val()。replace(/,/ gi,''))|| 0;
    var input5 = parseInt($('#tradeInValue')。val()。replace(/,/ gi,''))|| 0;
    var input6 = parseInt($('#amtOwedOnTrade')。val()。replace(/,/ gi,''))|| 0;
    var input7 = parseInt($('#extendedWarranty')。val()。replace(/,/ gi,''))|| 0;
    var input8 = parseInt($('#gapInsurance')。val()。replace(/,/ gi,''))|| 0;
    var input9 = parseInt($('#serviceContract')。val()。replace(/,/ gi,''))|| 0; (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);

    $('。total')。

    //如果我保留以下行并删除('input.number')函数,那么它工作正常。
    // $('。total')。text('$'+ sum.toFixed(2).replace(/(\ d)(?=(\ d {3})+ \。 )/ g,'$ 1,'));

    var total =(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);

    };
    });

    });
    //格式化显示的输入字段数字
    //如果我在下面保留这两个函数,那么它不会正确显示格式化数据。
    $(document).ready(function(){
    $('input.number')。keyup(function(event){
    // skip for arrow keys
    if (event.which> = 37&& event.which< = 40){
    event.preventDefault();
    }
    var $ this = $(this);
    var num = $ this.val()。replace(/,/ gi,).split()。reverse()。join();

    var num2 = RemoveRougeChar(num.replace(/(。{3})/ g,$ 1,)。split()。reverse()。join());

    console。 log(num2);

    $ this.val(num2);
    });
    });

    函数RemoveRougeChar(convertString){

    if(convertString.substring(0,1)==,){

    return convertString。 substring(1,convertString.length)

    }
    return convertString;


    //限制键
    函数isNumberKey(evt){
    var charCode =(evt.which)? evt.which:evt.keyCode
    if(charCode> 31&&(charCode< 48 || charCode> 57))
    return false;
    返回true;
    };

    演示: http://jsfiddle.net/IrvinDominin/LHn6X/6/


    I have multiple scripts handling the formatting of the inputs in a form (multi-part) form.

    I have one script doing the math and converting the total to a fixed number sum (thanks to Irvin Dominin link description here and ElendilTheTall for this):

    $(document).ready(function() {
        $(function() {
            $("body").on("blur", "#vehiclePrice, #estimatedTaxesAndFees, #downPayment, #manufacturerRebate, #tradeInValue, #amtOwedOnTrade, #extendedWarranty, #gapInsurance, #serviceContract", function() {
                updateTotal();
            });
    
            var updateTotal = function() {
                var input1 = parseInt($('#vehiclePrice').val()) || 0;
                var input2 = parseInt($('#estimatedTaxesAndFees').val()) || 0;
                var input3 = parseInt($('#downPayment').val()) || 0;
                var input4 = parseInt($('#manufacturerRebate').val()) || 0;    
                var input5 = parseInt($('#tradeInValue').val()) || 0;
                var input6 = parseInt($('#amtOwedOnTrade').val()) || 0;    
                var input7 = parseInt($('#extendedWarranty').val()) || 0;
                var input8 = parseInt($('#gapInsurance').val()) || 0;
                var input9 = parseInt($('#serviceContract').val()) || 0;     
    
                $('.total').text(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
                $('.total').text('$'+sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
    
                var total = (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
            };
        });
    });
    

    I have two functions handling the input fields and adding a comma:

    $(document).ready(function() {
        $('input.number').keyup(function(event) {
            // skip for arrow keys
            if (event.which >= 37 && event.which <= 40) {
                event.preventDefault();
            }
    
            var $this = $(this);
            var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
            var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
    
            console.log(num2);   
    
            // the following line has been simplified. Revision history contains original.
            $this.val(num2);
        });
    });
    
    function RemoveRougeChar(convertString) {   
        if (convertString.substring(0,1) == ",") {      
            return convertString.substring(1, convertString.length)                 
        }
    
        return convertString;   
    };
    

    Then yest another script preventing stripping out unwanted characters in the input fields:

    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : event.keyCode
    
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
    
        return true;
    };
    

    Ultimately what I am trying to do here is format the inputs with a comma, disallow any decimals, and then display a formatted value (only commas) in the div. All the while preventing any unwanted characters from being typed in the inputs.

    If I try and use all the scripts together, it will only display the first numbers of the input fields, i.e. the ones before the commas.

    Any ideas?

    Das Fiddle

    解决方案

    Currently there are three issues:

    1. the type="number" for you input elements allows, if the browser support it, you to enter only numbers, but you are appending , to your number so it natively clear the value, switch it into type="text"
    2. the sum is not performed in the right way because of the , try removing it using .replace(/,/gi,'') and then parse as number
    3. in the isNumberKey function you are using event instead of evt

    Code:

    $( document ).ready(function() {
    $(function() {
        $("body").on("blur", "#vehiclePrice,#estimatedTaxesAndFees,#downPayment,#manufacturerRebate,#tradeInValue,#amtOwedOnTrade,#extendedWarranty,#gapInsurance,#serviceContract", function () {
        updateTotal();
    });
        var updateTotal = function () {
        var input1 = parseInt($('#vehiclePrice').val().replace(/,/gi,'')) || 0;
        var input2 = parseInt($('#estimatedTaxesAndFees').val().replace(/,/gi,'')) || 0;
        var input3 = parseInt($('#downPayment').val().replace(/,/gi,'')) || 0;
        var input4 = parseInt($('#manufacturerRebate').val().replace(/,/gi,'')) || 0;    
        var input5 = parseInt($('#tradeInValue').val().replace(/,/gi,'')) || 0;
        var input6 = parseInt($('#amtOwedOnTrade').val().replace(/,/gi,'')) || 0;    
        var input7 = parseInt($('#extendedWarranty').val().replace(/,/gi,'')) || 0;
        var input8 = parseInt($('#gapInsurance').val().replace(/,/gi,'')) || 0;
        var input9 = parseInt($('#serviceContract').val().replace(/,/gi,'')) || 0;     
    
                $('.total').text(input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
    
            //If I keep the following line and remove the ('input.number') function then it works fine.
    //                      $('.total').text('$'+sum.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,'));
    
        var total = (input1 + input2 + input3 + input4 + input5 + input6 + input7 + input8 + input9);
    
         };
     });
    
    });
    //format the input fields displayed number
    //If I keep these two functions below, then it does not display the formatted data correctly. 
    $(document).ready(function(){
      $('input.number').keyup(function(event){
          // skip for arrow keys
          if(event.which >= 37 && event.which <= 40){
              event.preventDefault();
          }
          var $this = $(this);
          var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
    
          var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
    
          console.log(num2);
    
          $this.val(num2);
      });
    });
    
    function RemoveRougeChar(convertString){    
    
        if(convertString.substring(0,1) == ","){
    
            return convertString.substring(1, convertString.length)            
    
        }
        return convertString;
    
    }
    //restrict the keys
    function isNumberKey(evt){    
        var charCode = (evt.which) ? evt.which : evt.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    };
    

    Demo: http://jsfiddle.net/IrvinDominin/LHn6X/6/

    这篇关于使用逗号格式化输入字段,并以Div的形式显示为数字格式的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆