Marco
Marco

Reputation: 2737

How to find the closest input name attribute value

given the following html:

<input name="name goes here" type="text" value="value goes here">
<span class="suggestInput" data-type="tag">
<img src="../images/icons/wand.png" title="Suggest an input" alt="">
</span>

im trying to find the name attribute value of the closest input, the one above the class 'suggestInput' above. In my example, it should return name goes here

I've tried:

$(".suggestInput").click(function(event) {
    event.preventDefault();

   var test1 = $(this).closest("input").attr("name");
   var test2 = console.log($(this).find().closest("input").attr("name"));
});

and they both return 'undefined' ..

What's wrong?

Upvotes: 0

Views: 1422

Answers (2)

Felix
Felix

Reputation: 38102

You can use .prev() here because input is the immediate previous sibling of your span:

var test1 = $(this).prev().attr("name");

.closest() is not working because this method will traverse up the DOM tree and get closest matching ancestor which is not applicable in your case:

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

.closest() is used to find an ancestor element, in your case the input element is not a ancestor element of the span.suggestInput element, it is the previous sibling so use .prev() to find it

var test1 = $(this).prev("input").attr("name");

Upvotes: 5

Related Questions