How to get the value of the nearest jQuery input

I have several buttons on my page with the same class. When I click the button, I want to get the value of the nearest input field (remember that on my page there are several input boxes and buttons 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 the user clicks on the link ????

+7
jquery closest
source share
3 answers

Use .prev() if you are sure that they are next to each other. (This should be the fastest.)

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

This gets the previous item.

If there is a possibility that there will be another element between them, you can use .siblings() :

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

This will lead all siblings to the same <div> with the deleteid class.

+13
source share
 $(this).parent().find('.deleteid').attr('value'); 
+3
source share
 $(this).parent().find('.deleteid').attr('value'); 

It can (and it) causes performance issues. For example:

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

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

0
source share

All Articles