As per .closest()
docs,for each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree but here input with class input-tiny and keyHash is not the ancestor but its sibling then in that case try below answers.
Try using .siblings()
as shown :
$('.loadKey').click(function() {
alert($(this).siblings('.input-tiny.keyHash').val());
});
DEMO
As per your html structure .siblings()
shown above will work just fine but if you have other elements with class input-tiny and keyHash which are siblings of .loadKey
then try :last
selector :
$('.loadKey').click(function() {
alert( $(this).siblings('.input-tiny.keyHash:last').val() );
});
DEMO
OR
Use .prev()
as shown :
$('.loadKey').click(function() {
alert($(this).prev('.keyHash').val());
});
DEMO
OR
Use .prevAll()
with :first
selector as shown :
$('.loadKey').click(function() {
alert( $(this).prevAll('input:text[class="input-tiny keyHash"]:first').val() );
});
DEMO
OR
Use .parent()
as shown :
$('.loadKey').click(function() {
alert( $(this).parent().children('input:text[class="input-tiny keyHash"]').val())
});
DEMO
Don't use .live()
its deprecated since jquery version 1.7
(refer here) instead use .on()
as shown :
$(document).on('click','.loadKey',function() {
alert($(this).prev('.keyHash').val());
});
Note :- Above shown .on()
(event delegation) example is only be used when you are adding html dynamically inside DOM with jquery.