Using .closest on element in different parent element

Viewed 85

I am trying to get the value of an input field that is closest to my button. I am able to do so using a for loop whenever the button is pressed however I was wondering if it can be done using .closest? Below is my current code

$('.discount-code-btn').on('click', () => {
  $('.discount-code-field').each(function() {
    if ($(this).val().length != 0) {
      console.log($(this).val());
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-12 col-12">
    <input type="text" class="form-control discount-code-field" placeholder="Discount Code" style="font-size:10px" />
  </div>

</div>
<div class="row mt-1">
  <div class="col-md-12 col-12">
    <button type="submit" class="form-control btn discount-code-btn" style="background-color:var(--light_blue);color:var(--white);font-size:10px"><b>Apply</b></button>
  </div>
</div>

When I tried using closest, like this:

$('.discount-code-btn').on('click',()=>{
   var temp = $(this).closest('input.discount-code-field').val();
   console.log(temp);
})

It puts out undefined. Any idea how to go about this? Thank you for reading.

2 Answers

The answer is no. You can't use closest like this. closest traverse only up in the hierarchy and the input is not in upper level of the button.

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

https://api.jquery.com/closest/#closest1

BTW, $(this) is the window because of the arrow function. I believe that you meant it to be the button so you need to use a regular function.

Credits to @Karan

$('.discount-code-btn').on('click',function(){
    var temp = $(this).closest('.row').prev().find('.discount-code-field').val();
    console.log(temp);
})
Related