Jon Rubins
Jon Rubins

Reputation: 4413

Finding sibling right above "this" jquery

I'm having trouble selecting the right element with my jQuery code. This is what the DOM basically looks like:

<div class='bad_link'>
    <p><a href='...'>...</a></p>
    <p><a href='...'>...</a></p>
    <input type='text' size='100' name='....' />
    <input class='check_button' type='button' name='check_link' value='Check' />
</div>

I'm trying to grab the value of the input field that is right above the "Check" button, but I'm having trouble doing that.

This is my jQuery code right now:

$(document).ready(function() {
    $(".check_button").on('click', function() {
        window.alert($(this).siblings().find('input').text());
    });
});

How can I grab that value?? Thanks!

Upvotes: 1

Views: 1173

Answers (3)

Spencer Ruport
Spencer Ruport

Reputation: 35117

You may want to consider a different approach than this to find the element you want to perform an operation on. When you use siblings it ties your functionality really closely to your HTML which is generally considered bad form. It's hard to understand that just moving a tag or adding another can cause functionality to break.

Instead I'd recommend giving the element you want to work with a class. Something like obj_myElement_xxx where xxx is the id of the element. Then set an attribute in your button that corresponds to the id of the element so you can use:

$(".obj_myElement_" + $(this).attr("data-myElementId"))

to grab the element you're trying to manipulate.

Upvotes: 1

Paul
Paul

Reputation: 141827

Use prev() to select the previous sibling and val() to get the value of the input:

window.alert($(this).prev().val());

Upvotes: 2

thecodeparadox
thecodeparadox

Reputation: 87073

.prev() will select the previous element of checkbox.

    $(".check_button").on('click', function() {
        window.alert($(this).prev('input[type="text"]').val());
    });

$(this).prev().val(); is also an option

Upvotes: 5

Related Questions