2

Is there any way to increment a value using jQuery? I want to have the values in this format. ABC-000001, ABC-000002,... ABC-100000 etc.

3
  • 1
    show us what you have tried. Commented Jun 26, 2014 at 8:18
  • 3
    How about you split it into two - the ABC- part and then the numeric part - manipulate the numeric as appropriate, then output it padding it with zeores? Commented Jun 26, 2014 at 8:18
  • do want to have it in array? Commented Jun 26, 2014 at 8:28

5 Answers 5

3

See http://jsfiddle.net/Juw6h/

var a =0
for(var i=0;i<1000;i++)
{
    $("#test").append(" ABC-"+pad(i,4))
}


function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
Sign up to request clarification or add additional context in comments.

1 Comment

It would be better if you put the append after the for loop, concatenate the string in the for loop and afterwards add it to the append, so you dont call append 1000 times.
1

This is my answer, please test it, this way is too fast

value="ABC-100002";
i=0;
$("#incrase").click(function(){
 var newValue=value.split('-');
    var increase=newValue[1];
    increase++;
    value="ABC-"+increase;
    alert(increase)

})

DEMO

Comments

1

See: http://jsfiddle.net/np7Yv/

$("#add").click(function() {
   var cur = parseInt($("#incremental").data('value')),
       prefix = $("#incremental").data('prefix'),
       padded;

   cur++;

   padded = ('000'+cur).slice(-4); // Prefix three zeros, and get the last 4 chars
   $("#incremental").val(prefix + padded);
   $("#incremental").data('value', cur);
});

EDIT

For saving the id's with a cookie see: http://jsfiddle.net/ueZh3/

6 Comments

Thanks a lot Billy, this is exactly what I was looking for. need to have some modification, suppose i clicked the button 10 times, 10 ids are generated now..when i will open this form next time then the increment should be from 11. is it possible?
Your welcome, currently it doesn't remember your last id. You need to save the current id to a cookie or either to localstorage so that the next time you open this page it will know the last id. I'll get a example for you up in a bit.
Update new url jsfiddle.net/ueZh3 for an example with the ability to save the id to a cookie.
Thanks Billy, yes its working, But one more problem might come. As am looking in to code, seems you are storing it into local cookies, my requirement is anyone can hit your html from anywhere, then this should retain the increment as what exactly its working now. Is it possible? I mean when you tested it three time from there and count become three, now am hitting the same html now its should show me next count that is 4.
Ahh, I didn't get that requirement. In that case it's going to be very difficult to do this with JS and HTML only. You need to include a PHP script that keeps track of the current id in a DB or file, when somebody increment it you need to use an AJAX request to get the new incremented id that PHP generated and stored.
|
1

You can create a generator like construction:

function AutoIncrement(prefix, start)
{
    var index = +start || 1; // start is 1 by default

    // see also: http://stackoverflow.com/a/2998822/1338292
    function pad(num, size) 
    {
        var s = "00000" + num;
        return s.slice(-size);
    }

    return function() {
        return prefix + pad(index++, 6);
    };
}

To use it:

var nextId = AutoIncrement('ABC-');

console.log(nextId()); // "ABC-000001"
console.log(nextId()); // "ABC-000002"

To start from any number:

var nextId = AutoIncrement('ABC-', 15);
console.log(nextId()); // "ABC-000015"

Demo

1 Comment

+1 for the neat code. OP could use this together with my example.
0
Here is my local html file

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0-beta2.js"></script>
<script type="text/javascript">
var incremental = $("#incremental");

$("#add").click(function(e, reload) {
   var cur = utils.getCookie("lastId") || parseInt(incremental.data('value')),
       prefix = incremental.data('prefix'),
       padded;

    if(reload !== true) {
        cur++;
    }

    padded = ('000'+cur).slice(-4); // Prefix three zeros, and get the last 4 chars
    incremental.val(prefix + padded).data('value', cur);
    utils.setCookie("lastId", cur, 10);//name, value, days to rememer
});

var utils = {
    setCookie: function(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime()+(exdays*24*60*60*1000));
        var expires = "expires="+d.toGMTString();
        document.cookie = cname + "=" + cvalue + "; " + expires + "; path=/; domain=." + location.host;
    },

    getCookie: function(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i<ca.length; i++)  {
            var c = ca[i].trim();

            if (c.indexOf(name)==0)
                return c.substring(name.length,c.length);
        }
        return null;
    }
};

$("#add").trigger("click", [true]);
</script>
</head>
<body>

<input value="ABC-0000" data-value="0" data-prefix="ABC-" id="incremental">
<a href="#" id="add">Add incremental</a>
</body>
</html>

1 Comment

You're loading the javascript code before the rest of the document is generated. HTML is kinda dumb and executes your code before the actual document is generated. To avoid this you can add $(document).ready(function() { before and }); after you code. Like so: jsfiddle.net/c2FLG

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.