Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting closest input value from clicked element with jQuery

I have the following markup:

<div class="options">   <div class="quantity">      <label>Qty:</label>      <input type="text" name="quantity" value="1"/>   </div>   <div class="buttons">     <a href="#" class="add">Add Item</a>   </div> </div> 

I have a click event binded to the 'add' class using jQuery. When I click that, I'd like to get the value of name="quantity", but there are several places that 'add' is clicked and several quantity fields.

I'm trying to get the 'closest' input value. I've tried using 'closest' and 'findall' , but no luck.

Any idea how I can get this using jQuery? Thank you!

like image 758
David Avatar asked Dec 28 '11 19:12

David


People also ask

How do I get the closest div using jQuery?

The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.

What is closest tr in jQuery?

jQuery closest() Method The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on.

How do I find the closest element?

The closest() method searches up the DOM tree for elements which matches a specified CSS selector. The closest() method starts at the element itself, then the anchestors (parent, grandparent, ...) until a match is found. The closest() method returns null() if no match is found.


1 Answers

$(".add").on("click", function () {     var val = $(this).closest("div.options").find("input[name='quantity']").val(); }); 

The strategy here is:

  • Use closest to find the closest ancestor matching the given selector (in this case a div with class option)
  • Then use find to find the input with the given name using the attribute equals selector.
  • Finally, use val to retrieve the value of the input.
like image 92
Andrew Whitaker Avatar answered Oct 05 '22 23:10

Andrew Whitaker