0

I have an array.

var array = [0,1,2,4]; 
var index; 

Now i have four buttons. I may click on any button at random order, i need the index value to be updated as 0 for the first button clicked, 1 for the second button, 2 for the fourth button and 3 for the third button.

2
  • lol.. does this question sound weird Commented Apr 20, 2011 at 15:32
  • I didn't see a question which is why I was snarking.. but others seem to have figured it out so there you go. Commented Apr 20, 2011 at 15:33

3 Answers 3

1

Html:

<input type="button" onclick="javascript:SetIndex(this)" value="one" />
<input type="button" onclick="javascript:SetIndex(this)" value="two" />
<input type="button" onclick="javascript:SetIndex(this)" value="three" />
<input type="button" onclick="javascript:SetIndex(this)" value="four" />

JavaScript:

var array = [0,1,2,4]; 
var index = 0;

function SetIndex(obj)
{
    // check if index is out of range and it might be useful
    // to see if this button already has an index assigned
    if (index < array.length && isNaN(obj.index))
    {
        obj.title = array[index]; // hover to see index...
        obj.index = array[index];
        index++;
    }
}

working example: http://jsfiddle.net/hunter/eS4qy/

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Now ehr, what shall we do with it? Btw, you could have removed the javascript: part from the paste:P
1

is this is what you want:

<button onclick="index=0">1</button>
<button onclick="index=1">2</button>
<button onclick="index=2">3</button>
<button onclick="index=3">4</button>

?

Comments

1
<input type="button" onclick="javascript:setIndex(0)" value="one" />
<input type="button" onclick="javascript:setIndex(1)" value="two" />
<input type="button" onclick="javascript:setIndex(2)" value="three" />
<input type="button" onclick="javascript:setIndex(3)" value="four" />

<script type="text/javascript">
    var index = 0;

    function setIndex(i) {
       index = i;
    }
</script>

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.