Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add items to array with OnClick

Status
Not open for further replies.

Jcarr38

Programmer
Feb 16, 2007
27
US
I have this code right here. The array starts with one item in it but i have dynamic links in the front end page that say this:
<a href="#" onClick="javascript:testItems('image2')">test</a>
<a href="#" onClick="javascript:testItems('image3')">test</a>
<a href="#" onClick="javascript:testItems('image4')">test</a>

Not all pages will have an image2 or image 3 or 4 so everytime the link is clicked, i need to add the item to the array and i get it to add but once i click the item again, it's re-entering and i can see how it's entering but i need to basically say something like "if the array doesnt have the value, then add it to the array". I appreciate any help.

var newArray =new Array();
newArray[0] = "image1"

function testItems(id)
{
for (i=0;i<=newArray.length-1;i++)
{
if (newArray != id)
{
newArray[newArray.length] = id;
}
alert(newArray);

}

}
 
Use an associative array (also known as a map). You also don't need to prepend javascript: to your onclick events:
Code:
... onclick="testItems('image2');" ...

Cheers,
Jeff



[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
Or, modifying your original code slightly to return from the function call early if the value is found:
Code:
function testItems(id)
{
for (i=0;i<newArray.length;i++)
  {
  if (newArray[i] == id) return;
  }
var arrlength = newArray.length;
newArray[arrlength] = id;
alert(newArray[i]);
}

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top