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.