0

I want to change the value to the next number on each click...once it reaches the end it repeats from beginning...

http://jsfiddle.net/5nwt0u36/

html:

<button id="button">Click me</button>
<br />
<br />
<div id="info"></div>

javascript:

var arr = [10001, 10302, 12303, 11004, 10044];

$(document).on('click', '#button', function() {
    $.each(arr, function(key, val) {
        $('#info').text(arr[key]);
    });
    return false;
});

3 Answers 3

1

Just put the index into a var, i in this instance, and increment the value on each click. Also make sure to check if i is equal to the length of the array, if so reset it.

A JS Fiddle for you

var arr = [10001, 10302, 12303, 11004, 10044],
    i = 0;

$(document).on('click', '#button', function() {   
    if(i === arr.length){
        i = 0;   
    }

    $('#info').text(arr[i]);
    i++;
    return false;
});
Sign up to request clarification or add additional context in comments.

Comments

1

if you store an index and increment it on each click, should work

var arr = [10001, 10302, 12303, 11004, 10044];
var i = 0;
$(document).on('click', '#button', function() {
    i++;
    $('#info').text(arr[i%arr.length]);
    return false;
});

Comments

1

Pretty simple, get the current index of the current number, check the length, if at the end, repeat:

var arr = [10001, 10302, 12303, 11004, 10044];
$(document).on('click', '#button', function() {
    var current = parseInt($("#info").text(), 10),
        currentIndex = arr.indexOf(current);

    var value;
    if (currentIndex == (arr.length - 1)) {
        value = arr[0];
    } else {
        value = arr[++currentIndex];
    }

    $("#info").text(value);
});

Comments

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.