user983208
user983208

Reputation: 235

Get the href value of a previous HTML anchoer, <a>, using jQuery

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.

HTML:

<a href="#activityNotes[0].noteText">
    <input value="Add Another" name="addAnotherNote" type="submit" class="addAnother secondary" onclick="addAnotherNote();"/>
</a>

jQuery:

$(".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?

http://jsfiddle.net/5Twfc/2/

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

Answers (4)

FreeCandies
FreeCandies

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

icyrock.com
icyrock.com

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

Dan A.
Dan A.

Reputation: 2924

The prev function gets the previous sibling. You want the parent item:

$(this).parent().attr("href");

Upvotes: 0

joni_demon
joni_demon

Reputation: 666

To get the value of href try to use this

    $('a').attr('href');

Upvotes: 0

Related Questions