How to get value of nearest input Jquery
Asked Answered
M

3

7

I have multiple buttons on my page with the same class. When I click on a button I want to get the value of the nearest input box (remember there are multiple input boxes and buttons on my page with the same classes).

I have:

    $(".deletepostbutton").click(function() {

            var deleteid = $(this).closest('.deleteid').attr('value');

  });


<div class="microblogpostactions">
     <input type="text"  name="deleteid" class="deleteid" value="'.$row['id'].'" />
     <a href="Javascript:void[0]" class="deletepostbutton">Delete</a>
     </div>

<div class="microblogpostactions">
     <input type="text"  name="deleteid" class="deleteid" value="'.$row['id'].'" />
     <a href="Javascript:void[0]" class="deletepostbutton">Delete</a>
     </div>

How can I get the value of the nearest input and make my variable equal to it when a user clicks on the link????

Marabout answered 28/8, 2010 at 17:37 Comment(0)
B
13

Use .prev() if you're sure they're right next to each other. (This should be fastest.)

 var deleteid = $(this).prev().attr('value');

This gets the previous element.

If there's a chance that there will be another element in between, you could use .siblings():

 var deleteid = $(this).siblings('.deleteid').attr('value');

This will get all siblings inside the same <div> with the deleteid class.

Bast answered 28/8, 2010 at 17:38 Comment(0)
B
3
$(this).parent().find('.deleteid').attr('value');
Bel answered 28/8, 2010 at 17:40 Comment(0)
Y
0
$(this).parent().find('.deleteid').attr('value');

It may (and it does) cause problems with perfomance. For example:

$(this).parent().find('.deleteid').val(10);
alert($(this).parent().find('.deleteid').val());

Sometimes it returns the previous value of .deleteid (not 10)

Yore answered 21/9, 2011 at 18:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.