Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading