Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value of nearest input Jquery

Tags:

jquery

closest

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????

like image 931
user342391 Avatar asked Aug 28 '10 17:08

user342391


People also ask

What is closest tr in jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

How does closest work in jQuery?

The closest( selector ) method works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression.


2 Answers

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.

like image 165
user113716 Avatar answered Oct 09 '22 10:10

user113716


$(this).parent().find('.deleteid').attr('value');
like image 43
Alex Reitbort Avatar answered Oct 09 '22 11:10

Alex Reitbort