Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
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 selector.
- Now, find the input with the given name using the attribute equals selector.
- The last step is to use val() method to retrieve the value of the input.
The closest() method traverses up the DOM tree from the current element to find the first ancestor that matches the specified selector. Once you locate the closest parent container, you can use find() to search for the input element within that container.
Example
You can try to run the following code to get closest input value from clicked element with jQuery ?
<!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>
The output of the above code is ?
When you click the "Click" link, an alert box will display: 1
In this example, when the link with class add is clicked, the jQuery code finds the closest div with class content, then searches within it for an input element with name="rank", and retrieves its value using val().
Conclusion
Using jQuery's closest() method combined with find() and val() provides an effective way to retrieve input values from elements related to the clicked element, making it useful for dynamic form interactions.
