zzzzz
zzzzz

Reputation: 202

jQuery - closest input to current input

I have two divs with same class names with one input inside each. First one has id, second - no, I need get closest input to my input with id. I can't set an id to second input, or change class names of divs.

HTML -

<div class="picker">
     <input id="myInput"/>
</div>
<div class="picker">
     <input/> <-- which I need to get ->
</div>

I have tried to use something like below, but, this operation returns me the first input.

$("#myInput").closest("input")

Upvotes: 0

Views: 33

Answers (1)

epascarello
epascarello

Reputation: 207501

So you need to pick parent the "picker" and then you need to pick the next "picker" and then find the input.

const inp = $("#myInput").closest('.picker').next('.picker').find('input');
inp.val('found it');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="picker">
  <input id="myInput" />
</div>
<div class="picker">
  <input/>
  <-- which I need to get ->
</div>

Upvotes: 1

Related Questions