theJava
theJava

Reputation: 15034

Selecting values from Array

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.

Upvotes: 0

Views: 1587

Answers (3)

hunter
hunter

Reputation: 63512

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/

Upvotes: 1

Liv
Liv

Reputation: 6124

<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>

Upvotes: 1

BiAiB
BiAiB

Reputation: 14122

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>

?

Upvotes: 1

Related Questions