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!
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.
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.
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.
$(".add").on("click", function () {     var val = $(this).closest("div.options").find("input[name='quantity']").val(); });   The strategy here is:
closest to find the closest ancestor matching the given selector (in this case a div with class option)find to find the input with the given name using the attribute equals selector.val to retrieve the value of the input.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With