Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery breaks the formatting of the page

The formatting of my page is incorrect when I add the following code:

$('#Inventory_accountNumber').blur(function(){
    var accounts = $(this).val();
    accounts = accounts.replace(/-/g,'');
    var accountNum = [];
    accountNum = accounts.split(",");
    for(var i=0;i<accountNum.length;i++) {
        var newstr = '';
        if(accountNum[i].length == 24) {
            newstr += accountNum[i].substring(0,4) + '-';
            newstr += accountNum[i].substring(4,7) + '-';
            newstr += accountNum[i].substring(7,10) + '-';
            newstr += accountNum[i].substring(10,14) + '-';
            newstr += accountNum[i].substring(14,20) + '-';
            newstr += accountNum[i].substring(20,24) + '-';
            newstr += '0000-000';
            accountNum[i] = newstr;
        }
        else if(accountNum[i].length == 31) {
            newstr += accountNum[i].substring(0,4) + '-';
            newstr += accountNum[i].substring(4,7) + '-';
            newstr += accountNum[i].substring(7,10) + '-';
            newstr += accountNum[i].substring(10,14) + '-';
            newstr += accountNum[i].substring(14,20) + '-';
            newstr += accountNum[i].substring(20,24) + '-';
            newstr += accountNum[i].substring(24,28) + '-';
            newstr += accountNum[i].substring(28,31);
            accountNum[i] = newstr;
        }
    }
    accountNum.join(',');
    $(this).val(accountNum);

});

The jsfiddle illustrates this code in use: http://jsfiddle.net/Lwv4U/14/

As you can see, it works in the jsfiddle, but on the live formatting issues are present. The screenshots below depict the page with and without the code added. This code is the only change in the code between the two code bases. If it matters Yii is being used as a framework.

Before before

After after

like image 492
ComputerLocus Avatar asked Nov 29 '25 21:11

ComputerLocus


1 Answers

jsfiddle.net/Lwv4U/25

JS:

$('#Inventory_accountNumber').blur(function(){
  $(this).val(function(index, value){
    var str = value.replace(/[^\d]/g,'');
    if (str.length < 10) return str;  
    return str.match(/(\d{4})?(\d{3})?(\d{3})?(\d{4})?(\d{6})?(\d{4})?(\d{4})?(\d+)?/)
    .slice(1).join("-").replace(/\-+/g,'-');
  });
});
like image 82
Daniel Avatar answered Dec 02 '25 12:12

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!