74

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>
Hexaholic
  • 3,299
  • 7
  • 30
  • 39
imperium2335
  • 23,402
  • 38
  • 111
  • 190

4 Answers4

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

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

Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 1
    Is there no other function that looks for something on the same level as the element you're currently on? Do you always have to go up and back down? – Majo0od Jan 11 '16 at 19:41
  • 3
    This question wasn't about finding something on the same level - it was necessary to go up then back down - but yes, for the same level there's `.siblings()` and various `next~()` and `prev~()` methods. – Mitya Jan 11 '16 at 20:22
  • 2
    thanks I was looking for a solution like that and it worked for me! but most important i learn more about closest() function. Thank you so much! Davide, – P.Davide Aug 03 '16 at 23:12
  • 1
    Thanks tired with almost everything at last it worked for me :) – Arzon Barua Aug 06 '17 at 07:27
14

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

$(this).closest('.row').children('.column').find('.inputQty').val();
Nagendra Rao
  • 7,016
  • 5
  • 54
  • 92
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

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/

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

You could try:

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

Alex
  • 7,320
  • 1
  • 18
  • 31