0

I am struck how to start counter with five digit counter. on button click. A request will go to server via ajax to store current value,so every time a new user will come if he press the button the counter will increase by 1.

    00001
    00002
    .
    00010
    .
    .
    99999

        $("#update").click(function() {
            $('#counter').html(function(i, val) {
                /*$.ajax({
                    url: '/path/to/script/',
                    type: 'POST',
                    data: {increment: true},
                    success: function() { alert('Request has returned') }
                });*/
                return + val+1;
            });
        });

<button id="update" type="button">Click Me</button>
<div id="counter">00000</div>
user2451541
  • 71
  • 3
  • 12

3 Answers3

3

You need to parse into int, increase and then parse to a string and to add it the "00000", then sub the unneeded zeroes.

 function increment(num) {
    var newNumber = parseInt(num) + 1
    var str = "00000" + newNumber;
    return str.substr(str.length-5);
}



   $("#update").click(function() {
            $('#counter').html(function(i, val) {
                /*$.ajax({
                    url: '/path/to/script/',
                    type: 'POST',
                    data: {increment: true},
                    success: function() { alert('Request has returned') }
                });*/
                return increment(val)
            });
        });





<button id="update" type="button">Click Me</button>
<div id="counter">00000</div>

fiddle - http://fiddle.jshell.net/L3mRD/2/

griffon vulture
  • 6,594
  • 6
  • 36
  • 57
  • Thanks, can you explain me this var s = num +""; , if i want to send the current counter value of id="counter" and then increment it by 1, can i do this? – user2451541 Jun 25 '14 at 11:50
0

There is no build in way to do what you want - but it's very easy to build yourself. See this stackoverflow containing some good points: How to output integers with leading zeros in JavaScript

Most likely you can use this slightly (performance) optimized function:

function pad(num, size) {
    return ('000000000' + num).substr(-size);
}

Or even "optimize" (read: simplify usage of) the function even further for a specific "size", if you know you always need e.g. 5 digits in total.

function pad5(num) {
    return ('0000' + num).substr(-5);
}
Community
  • 1
  • 1
Nick Niebling
  • 317
  • 3
  • 12
0

1)Make ajax call on each button click.

2) call server side php file on every ajax call.

3) In php file fire below query:

UPDATE tablename SET tnumber = tnumber +1

It's automatically update your counter on button click.