如何使用javascript从循环中的字段获取信息

I have a bunch of image names that is being retrieved from my data base and is in a while loop. In this loop I have a small form with the image names. This form is being use for another purpose. what I want is to get the field information with the item name to a javascript.

Example :

while($row = mysql_fetch_array($query)) { 
    $itemname = $row['name'];
    echo "< input type='hidden' name='$itemname' value='$itemname'>
    <img src='source' onclick='getname()'  width='100%' height='100%' />"; 
}

I believe the reason why every image I click on is only giving me the first information from the database is because my id is being duplicated. My question is how can I get the field information to javascript without using the getElementById?

Use the following altered PHP:

$i = 0;
while($row = mysql_fetch_array($query)) { 
    $itemname = $row['name']; 
     echo "<input type='hidden' name='".$itemname."[]' id='input$i' value='$itemname' />";
     echo "<img src='source' onclick=\"getname('input$i')\" width='100%' height='100%' />"; 
     $i++;
}

Then you can retrieve the input value in Javascript:

 function getname(id) {
   var theinput = $('#'+id).val(); // jQuery example
   // do something

(I also changed the input name to be an array, of couse you could name it what you want, maybe $itemname$i could be an idea, it depends how and if you want to process your form, however the name should be unique or array for good practice)

Here is a working example of HTML/JS: http://jsfiddle.net/fuHSv/1/

How about using some jQuery 1.8.2 like the following:

$(document).ready(function() {
    var inputs = $('input').on('click', function() {
        var name = $(this).attr('name');
        var val = $(this).val();
        // do stuff
    });
});

See api.jquery.com for more.