Jquery find nearest matching element

JqueryDom Traversal

Jquery Problem Overview


I have a series of rows with columns and I want to select the value of an input field that is in a previous column to the input field (price input) that I am calling a function on when a key is released.

I have tried:

quantity = $(this).parent().parent().children().val() ;
quantity = $(this).parent().parent().children().closest('.inputQty', this).val() ;

But neither work.

An example of the DOM:

<div class="row">
    <div class="column"><input class="inputQty" id="quantity0" /></div>
    <div class="column"><input class="someOther" id="Other0" /></div>
    <div class="column">
        <div class="cSelect">
            <select id="currency0"><option>£</option></select>
            <input class="price" id="price0" />
        </div>
    </div>
</div>

Jquery Solutions


Solution 1 - Jquery

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

Solution 2 - Jquery

closest() only looks for parents, I'm guessing what you really want is .find()

$(this).closest('.row').children('.column').find('.inputQty').val();

Solution 3 - Jquery

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

Solution 4 - Jquery

You could try:

$(this).closest(".column").prev().find(".inputQty").val();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionimperium2335View Question on Stackoverflow
Solution 1 - JqueryMityaView Answer on Stackoverflow
Solution 2 - JqueryadeneoView Answer on Stackoverflow
Solution 3 - JqueryEsailijaView Answer on Stackoverflow
Solution 4 - JqueryAlexView Answer on Stackoverflow