How to get the closest input value from clicked element with jQuery?



To get the closest input value from clicked element with jQuery, follow the steps −

  • You need to use closest to find the closest ancestor matching the given.
  • Now, find the input with the given name using the attribute equals selector.
  • The last step is to use val() metjod to retrieve the value of the input.

Let’s first see how to add jQuery −

Example

You can try to run the following code to get closest input value from clicked element with jQuery −

Live Demo

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
             $(".add").on("click", function () {
                var v = $(this).closest("div.content").find("input[name=’rank’]").val();
                alert(v);
             });
         });
      </script>
   </head>
<body>
  <div class="content">
     <div class="ranking">
        <label>Rank:</label>
        <input type="text" name="rank" value="1"/>
     </div>
     <div class="buttons">
        <a href="#" class="add">Click</a>
     </div>
  </div>  
</body>
</html>

Advertisements