Bogdan Tushevskyi Bogdan Tushevskyi - 5 months ago 10
jQuery Question

check value of input field

I have structure like this. On button click jquery code make border of input red if field is empty. Everything works fine with first row. At others row border become red after button click even if i put valid value.



$('.btn-submit').click(function(){
var value = $(':input').val();
if(!value.length) {
$(this).parents('.row').find(':input').css('border-color','#f00');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>
<div class='row'>
<input>
<button class='btn-submit'>Check</button>
</div>




Answer

When any button is clicked, it is checking the value of the first <input>.

Change this line:

var value = $(':input').val();

To this:

var value = $(this).prev(":input").val();

This should select the <input> element directly before the button.


Another tip: You seem to try to find the child input of the parent using jQuery. Instead, you can find the sibling, using something like prev() (which will work in your case).

Comments