TopTomato
TopTomato

Reputation: 585

How do i access an input value that is up one level, and then a sibling of, using jQuery

i have a page that contains numerous divs like what is shown below, it is a page of color swatches, ie thumb size images. what i have to do is this: when the user mouses over an image swatch, it has to display the value of the input field who's name is 'descriptive name'. the difficulty i'm having is accessing that input field's value. the image is nested in a label. the label and the input field are siblings.,

my pseudo code is something like this:

$('label.color-options img').each(function(){
$(this).mouseover(function(){
    var descriptiveName = $(this).upOneLevel().sibling().('input.swatch-    desciptive-name').value);
    $('#display-descriptive-name').html(descriptiveName);
}) })

the page mark up is this:

<div id="display-name"> </div>
<!-- END MAIN PRODUCT IMAGE -->
<!-- the page is full of these color swatches -->
<div class="color-swatch-wrapper">
<input type="hidden" value="Avacado 77" name="descriptive-name" class="swatch-descriptive-name" /> 
<input type="radio" name="id[10]" value="129" id="attrib-10-129" class="color-swatch-radio-btn" />
<label class="attribsRadioButton color-options" for="attrib-10-129">
    PP77<br />
    <img src="images/attributes/artichoke_green.jpg" alt="" width="260" height="320" />
</label>
</div>

big thanks in advance

Upvotes: 1

Views: 99

Answers (2)

bnice7
bnice7

Reputation: 45

Try something like this:

var descriptiveName = $(this).parent().parent().find('input.swatch-descriptive-name').val();

Check the spelling of "descriptive" in your CSS class.

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

First off, you don't need to attach your event handlers in a loop, and to get the value of an input element you can use val().

You can use parent().siblings(), like this:

$('label.color-options img').mouseover(function(){
    var descriptiveName = $(this).parent().siblings('input.swatch-desciptive-name').val();
    $('#display-descriptive-name').html(descriptiveName);
});

Or alternatively, you can use closest() and find():

$('label.color-options img').mouseover(function(){
    var descriptiveName = $(this).closest('.color-swatch-wrapper').find('input.swatch-desciptive-name').val();
    $('#display-descriptive-name').html(descriptiveName);
});

I would recommend the latter as it will not break if you change the HTML structure of those elements, so long as the class names remain.

Upvotes: 4

Related Questions