Hi all
I want to access hidden values by javascript
what's wrong on bellow code:


<html>
<head>
<script language="javascript">
function func(i)
{
var x=document.form1.array.value;
alert(x);
}
</script>
</head>

<body>

<form method=post name=form1>
<?php
for($i=1;$i<100;$i++)
{
echo "<input type=hidden name=array[$i] value=$i>";
echo "<input type=button onclick=func($i) value=$i>";
}
?>

</form>

</body>
</html>

Dude I already wrote out this long ass answer and was about to hit send and then got distracted by my brother, afterwards i clicked a link below and lost it all....so I'll keep it short this time.

Bluntly, name = array[num] is wrong. The javascript will never find the element you are looking for that way (i tried to explain this before but im too lazy now).

If you are interested in another solution...
Replace the first echo with:

echo "<input type=\"hidden\" name=\"$i\" value=\"$i\">";

...and the javascript x assignments with:

document.getElementsByName(i)[0].value;

The php change simplifies your problem by giving each hidden element a plain numeric name.

The javascript method document.getElementsByName(elname) searches the document for elements named elname and returns an array containing all the matches, which is why I had to access the elements through [0] (note: each of these elements will be the sole elements in their respective arrays, so I can get off with using the index 0 everytime).

Now the code works as you wanted (I think).

May I suggest using Firefox for javascript debugging? The Error Console (Tools -> Error Console) provides some nice error messages that will help you sort things out.

HTH

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.