user570782
user570782

Reputation: 116

how to grab a value using a link

i am trying to bind an id to a tag. not sure if i should do a bind but i hope my example would help to explain what i am trying to do. i have a php for loop that gives me a series of numbers

<?php

         for($value = 1; $value <=5; $value++){
         print '<br><form><input id="hidden" type="hidden" value="'.$value.'" /><a id="link">click here</a><form>';
         }
         ?>

in my html i have a field within a form when the while loop is executed html looks like this

<input id="hidden" type="hidden" value="1" /><a id="link">click here</a>
<input id="hidden" type="hidden" value="2" /><a id="link">click here</a>
<input id="hidden" type="hidden" value="3" /><a id="link">click here</a>

my aim is this. if i click on the first 'click here' i want to output the hidden value of 1 if i click on the second 'click here' i want to output hidden value of 2 and etc.. my problem is that when i click on either link, i only get back the value of the first 'click here' which is 1

this is my jquery code.

<script>
$(document).ready(function(){ 
    $("a#link").click(function(){
    var s = $('.hidden').val();
 alert(s); 
 }); 
}); 
</script>

thanks for your help in advance...

Upvotes: 0

Views: 73

Answers (3)

The Alpha
The Alpha

Reputation: 146191

ID should be unique, you can use class='hidden' instead of id="hidden" and in your function you have used var s = $('.hidden').val() but there is no 'hidden' class in your form.

Upvotes: 0

Rafay
Rafay

Reputation: 31033

never ever use the identical ids change it to class

<input id="hidden" type="hidden" value="1" />
<a class="link" href="#">click here</a>
<input id="hidden" type="hidden" value="2" />
<a class="link">click here</a>
<input id="hidden" type="hidden" value="3" />
<a class="link">click here</a>

and the jquery part has already been answered by @DavidGouge

    $("a.link").click(function(e){
     e.preventDefault();
     var s = $(this).prev("input").val();
 alert(s);
 });

DEMO

Upvotes: 1

DavidGouge
DavidGouge

Reputation: 4623

$('.hidden').val()

will always just give you the first hidden val in the DOM. You need

$(this).prev("#hidden").val()

See this fiddle: http://jsfiddle.net/RJJEr/

Upvotes: 1

Related Questions