Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery find nearest matching element

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>
like image 623
imperium2335 Avatar asked Aug 01 '12 09:08

imperium2335


People also ask

What is closest in jQuery?

The closest() is an inbuilt method in jQuery that returns the first ancestor of the selected element in the DOM tree. This method traverse upwards from the current element in the search of first ancestor of the element.

How can I get next sibling in jQuery?

jQuery next() Method The next() method returns the next sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse forward along the next sibling of DOM elements.

How do I find a specific parent in jQuery?

jQuery | parent() & parents() with ExamplesThe parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element.


3 Answers

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

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

like image 125
Mitya Avatar answered Oct 03 '22 20:10

Mitya


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

$(this).closest('.row').children('.column').find('.inputQty').val();
like image 24
adeneo Avatar answered Oct 03 '22 20:10

adeneo


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/

like image 23
Esailija Avatar answered Oct 03 '22 21:10

Esailija