0

I've spent the past hour trying to figure this out and I can't seem to get it right. I've only just started learning jQuery but I feel I'm getting close to a solution for this problem of mine.

I have two divs.

HTML

<div class="fl person"> 
     <input type="hidden" name="userSaved" id="userSaved" value="1" /> 
     <img src="..." class="circle-mask" /> 
</div>

<div class="fl person"> 
     <input type="hidden" name="userSaved" id="userSaved" value="2" /> 
     <img src="..." class="circle-mask" /> 
</div>

I want to be able to get the hidden value (there's a form outside of all of this, I just didn't include it as it would just take up more room) from which ever div/image is clicked. When an image is clicked it hides that div. My jQuery for the value is quite off. I've had it so it gets the value but only from the first div, I can't seem to get it so that it displays the value of the hidden input from which ever div is clicked.

jQuery

<script>
$("div.person img").click(function () {    
    $(this).hide(500, function () {
        var $hidden = $('input#userSaved');
        alert($hidden.val());
        $(this).parent("div").empty();
        $(".main_page").appendTo("div.main_page").addClass("fl person"); 
    });
});
</script>

Also, how do I access $hidden outside of the function?

halfer
  • 19,824
  • 17
  • 99
  • 186
PaulEx10
  • 155
  • 2
  • 10
  • 1
    Don't use an `id` more than once. It should be `` if you're using it multiple times. – ayyp Jul 18 '13 at 17:23

2 Answers2

2

Use the siblings() function:

var $hidden = $(this).siblings('input');

prev() would also work:

var $hidden = $(this).prev();

Side note: Your code has multiple elements with the same id, which is invalid. You should change that.

Edited to simplify the changed part.

Jason P
  • 26,984
  • 3
  • 31
  • 45
  • That works perfectly. Oops, didn't spot I used it twice; changed it now though. Thanks again. – PaulEx10 Jul 18 '13 at 17:29
  • How do I access $hidden outside of the function? – PaulEx10 Jul 18 '13 at 17:48
  • As it is now, you can't. Need more context to answer that. That sounds like a different question though. – Jason P Jul 18 '13 at 17:49
  • Hmm okay. I've just put up a new question with more context: http://stackoverflow.com/questions/17730675/asking-variable-outside-of-function - any help is greatly appreciated! – PaulEx10 Jul 18 '13 at 17:54
0

You can also traverse to it with this:

 var $hidden = $(this).parent('div').find('input:hidden');

OR

var $hidden = $(this).prev();

Demo

Note: Ids should be unique, don't use duplicate Ids

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68