Account Number Live Update

Updates the account number to be formatted in the correct manner!

by Fogest

HTML

<input size="60" maxlength="247" name="Inventory[accountNumber]" id="Inventory_accountNumber" type="text" value="2951100100000000000062060169000" style="background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAALHRFWHRDcmVhdGlvbiBUaW1lAEZyaSAxMiBOb3YgMjAxMCAxOTowNzowMiArMTIwMOGr8p4AAAAHdElNRQfaCwwGBxwduq16AAAACXBIWXMAAAsSAAALEgHS3X78AAAABGdBTUEAALGPC/xhBQAAAfJJREFUeNqVkk1vElEUhp87X4CIFhhMG0toMC5K3Lgxbro10bhxY2Jc+CO666Y/oP/DxFVjTKM7l1apTdM0JSU0LSg0WqaUjwE6MDNebGpKBYlndc+55zw5H6/gim2UUd0qs5Uy6VaTa7EYdtOmUN7naHER92q+dtnZ2UFpHTOTXWfuwxrfYlNUHz1lxvdIVyx6MuXHPwFeBLW2z+29Pepr7ziUof7SEq1CibCEmKMAymXH6SD6LrpzRndQPIjNz9P3odu2URlhQ4C+ghcM0JpLEchkzrv7eIDS62JYP2lPBJS2cIMhyrMpwo+fMbW8jLhhc2t3F906pjoK8GcH29vonoenRDk1m5zcvUM6ZuJvZEnmcljT09hbR6iVIuLJw/PxhgAOPOj26Gk1nEQCNWAQ7XS4bxvw8hWuGedeo4iR+/y7+OtfgM1N9OIBwnFQ5SLdZJJ2JML17BdqEuYHgmiahsjnx4zw/i2fslm8dht/YQHx/AWpfI50/ZTKm9d8lykiHkf4/hjA6ipnF++VFRS7T1AoaDejyCEYlHmWNeEKF9YISz30CBkGirxKUIZGamAsQG2hux66BAipi1A6g/5fAM/HkGrUFfmr6wSSiWHJTwQoPrq8hCYEGDoh0xzfwUhyIY9ROkRrNKQ65e1P6uM7+AW+ibcHEM1ixAAAAABJRU5ErkJggg==); background-position: 373px 0px; background-repeat: no-repeat no-repeat;">

JavaScript

$('#Inventory_accountNumber').blur(function(){
        //chained functions to shorten, no need to declare array first split will create one
		var accountNum = $(this).val().replace(/-/g,'').split(",");
        
		for(var i=0;i<accountNum.length;i++) {
			if(accountNum[i].length == 24) {
               //your dash substring matches were the same up through the first 24 digits, so instead you can just add the extra 7 zeros and then process under the 31 digit rule
               accountNum[i] += '0000000';
			}
			if(accountNum[i].length == 31) {
                //used regex to combine the all the substrings into 1 rule
                accountNum[i] = accountNum[i].replace(
                    /(\d{4})(\d{3})(\d{3})(\d{4})(\d{6})(\d{4})(\d{4})(\d+)/
                    ,"$1-$2-$3-$4-$5-$6-$7-$8");
            }
		}
		accountNum.join(',');
		$(this).val(accountNum);
	});