Sunil Chaudhry Sunil Chaudhry - 6 months ago 28
Javascript Question

Find first visible input text with blank value having attribute required

I want to create a jQuery function for first visible input text with blank value having attribute required (without each function if doable).

$("input[type='text'][value='']").eq(0).on(function(){
// code
});

Answer

Use filter() and :visible

$("input[type='text']:visible[required]").filter(function() {
  return this.value.trim() == '';
}).eq(0).css('border', '1px solid red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" style="display:none">
<input type="text">
<input type="text" required>
<input type="text" required>


If value attribute is need to check then

$("input[type='text']:visible[required][value='']").eq(0).css('border', '1px solid red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" style="display:none" value=''>
<input type="text" value=''>
<input type="text" value='' required>
<input type="text" value='' required>