ohboy21
ohboy21

Reputation: 4319

How to add digits to different spans with JavaScript?

I have a variable which counts an amount of elements:

var n = 0;

Now, if I make

n++;

i want to apply this number to different digits:

<span class="n">-</span>
<span class="n">-</span>
<span class="n">-</span>
<span class="n">-</span>

If i have the number 10, I want:

<span class="n">-</span>
<span class="n">-</span>
<span class="n">1</span>
<span class="n">0</span>

How can i do this?

I want to build my own counter. I can use jQuery / JavaScript or whatever the Web has to offer.

Upvotes: 1

Views: 97

Answers (3)

binaryatrocity
binaryatrocity

Reputation: 976

You want to split the digits into an array and assign accordingly:

var n =  101;
n++;
var digits = (""+n).split("");

Now you have an array digits that you can assign out:

digits[0] = 1
digits[1] = 0
digits[2] = 2

Update Just an idea, instead of creating the SPAN's ahead of time, you could use a container and create them dynamically:

<div id="counter"></div>

function setCounter(n) {
    digits = (""+n).split("");
    digits.forEach(function(index){
        $("#counter").append("<span class='digit'>"+index+"</span>");
    });
}

Here is a working JSFiddle using the code above.

Upvotes: 3

dfsq
dfsq

Reputation: 193311

Try this code:

var n = 0,
    placeholders = document.getElementsByClassName('n');

function updateView(number) {
    ('' + number).split('').reverse().forEach(function(el, i) {
        placeholders[placeholders.length - i - 1].innerHTML = el;
    });    
}

Pass any number in this function and its digits will be placed in proper positions. E.g.:

updateView(85); // => --85

(sorry, I don't know how to name this function better)

Demo: http://jsfiddle.net/6dZmT/1/

Upvotes: 1

Jim Noble
Jim Noble

Reputation: 552

I am assuming from your example that your counter never goes above four digits. So we can convert the number to a string and build markup by iterating over its characters.

I made a jsfiddle to demonstrate http://jsfiddle.net/H4wQ8/

But the core of it is this javascript:

var n = 0;

function buildCounter(number)
{
    var markup = '';

    var numberString = String(number);

    for (var i = 0; i < 4 - numberString.length; i++)
    {
        markup += '<span class="n">-</span>';
    }

    for (var i = 0; i < numberString.length; i++)
    {
        markup += '<span class="n">' + numberString[i] + '</span>';
    }

    $('#counter').html(markup);
}

$(function ()
{
    $('#incrementButton').on('click', function ()
    {
        n++;

        buildCounter(n);
    });

    buildCounter(n);
});

We use a helper function to build the markup, and jquery to place it in the appropriate container.

Upvotes: 0

Related Questions