Reputation: 235
I am trying to get the value of href of <a> that is the previous element to my current button that is clicked. How do I get it?
Here is my code.
<a href="#activityNotes[0].noteText">
<input value="Add Another" name="addAnotherNote" type="submit" class="addAnother secondary" onclick="addAnotherNote();"/>
</a>
$(".addAnother").click(function() {
var jump = $(this).prev("a").attr("href");
});
When I try running this, I get
jump value undefined.
Why is this happening? Is it because I'm trying to get an anchor with #
in front?
Actually I am trying to get the display to anchor section with name/id = activityNotes[0].noteText
when I click on the add button. That is the reason I have this input button inside the <a>. Also, I am doing a form submit after I run few scripts.
$(".addAnother").click(function() {
var jump = $(this).parent().attr("href");
var new_position = $('#'+jump).offset();
window.scrollTo(new_position.left,new_position.top);
return false;
});
Upvotes: 0
Views: 2435
Reputation: 1113
That's because this points to the input. To get the anchor either move the class to it or use the following:
$(this).parent().prev("a").attr("href")
Upvotes: 0
Reputation: 28618
Your a
encloses input
. prev
gets previous sibling. In this case, you need to get the parent. Here's what will work based on your jsFiddle:
$(".addAnother").click(function() {
var jump = $(this).parent().attr('href');
$('#printJumpValue').text('' + jump);
})
and a live example:
Upvotes: 2
Reputation: 2924
The prev function gets the previous sibling. You want the parent item:
$(this).parent().attr("href");
Upvotes: 0