I need one help.I have one value ('i.e-001') which datatype is varchar and i convert this into integer and then want to add 1 at each time DB entry.I did something like below.
var newcode=parseInt(response.data.code)+1;
Here response.data.code contains the code 001 and its coming from DB.first user is fetching the latest code(i.e-001) from db and increment by 1 then storing in the DB.In this case i am getting newcode value is 2 but I should get 002,'003',..so on.Please help me.
4 Answers 4
Use a small function:
<script>
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
var len = response.data.code.length;
var newcode=parseInt(response.data.code)+1;
alert(pad(newcode, len));
</script>
1 Comment
response.data.code is 011 it is giving the output 010 and also 4 digit case its giving the different output.After incrementing do the padding again
var originalLength = response.data.code.length; //to ensure that new number is of same length
var newcode=parseInt(response.data.code)+1;
while( newcode.toString().length < originalLength ) //assuming that you want length 3
{
newcode= "0" + newcode;
}
alert( newcode );
2 Comments
newcode.toString() in the while loop instead of newcode+""? They both work the same but toString would make it much more readable.When you do parseInt Javascript removes 00 before the number and you get exact 1.
So if you add 1 you get 2.
If you want to get 002 you should try
var newcode= '00'+parseInt(response.data.code)+1;
For 10 digits just loop it:
for(var i=0; i<10-newcode.length; i++){
newcode = '0'+newcode;
}
But the best solution was provided by YeldarKurgmangaliev.
It's terrible mistake to generate ID in jQuery, do it in database.
7 Comments
017, it will become 0018 which seems to be incorrect.Try using String.prototype.replace() with RegExp /(\d+$)/ to match digit characters
var str = "i.e-009";
str = str.replace(/(\d+$)/, function(match) {
var n = Number(match) + 1, len = String(n).length
// if `n` equals `9` , return `"i.e-009"`
// if `n` equals `10`, return `"i.e-010"`
// if `n` equals `100` rerurn `"i.e-100"`
, res = len === 1 ? "00" : len === 2 && "0" || len === 3 && "";
return res + n
});
console.log(str)
002is not a validjsinteger