Hello Everyone, I'm trying to write a simple javascript function that is based on addition. I'm having a chain of products with unique id's with follwoing formats: CA-XXXX Here XXXX is a 4 digit number... starting from 0001, 0002, 0003 and so onwards... I have a page where the user can enter 5 products to the database. The unique ID's are generated by my JavaScript function. The previous unique id from the Database is fetched by JavaScript and then i start doing the addition. Here is my function: function nextProducts() { //get the last available product already in the database, fetched from unique id last_product somewhere as hidden id on the page var str1 = document.getElementById("last_product").value; var productId = "product_number"; var length = str1.length; prefix = str1.substring(0,2); if (prefix == "CA" || prefix == "LU") { //here i'm extracting the last 4 digits from ID such as CA-XXXX, BV-XXXX, or LU-XXXX suffix = str1.substring(length-4,length); prefix = str1.substring(0,2); } else if (prefix == "BV") { suffix = str1.substring(length-4,length); prefix = str1.substring(0,3); } else { suffix = str1.substring(0,length); prefix = ""; } for (i = 1; i<=5 ; i++ ) { //here's the problem... //when i use parseInt function 0001 is converted into only 1 and next product id is shown as 2 to me.. //if i dont use the parseInt function, then suffix is treated as a string and i get 00011 as the result... suffix = parseInt(suffix) + 1; newProd = prefix+suffix; var product2 = productId + i; document.getElementById(product2).value = newProd; } } PHP:
You will need to add leading zeros manually function padZeros(num, totalLen) { var numStr = num.toString(); var numZeros = totalLen - numStr.length; if (numZeros > 0) { for (var i = 1; i <= numZeros; i++) { numStr = "0" + numStr; } } return numStr; } Code (markup): The use: suffix = padZeros(parseInt(suffix) + 1, 4); Code (markup):