OMiD OMiD - 1 month ago 19
jQuery Question

change background color if elements are empty with jquery

I have 2 textboxs, 1 select and 1 file.

How can I chage their background color with jquery if they are empty.

I want to check all of them with a for loop.

<input type="text">
<input type="text">

<select>
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>

<input type="file">

Answer

I approached it as creating a named function and calling that function on the initital page load and then calling the function again on each on the entering of information into the inputs. Note that I just changed the function from direclty adding css to the elements - to adding / removing a class ('invalid') to the inputs. It is always better to toggle a class than to directly affect the CSS of a single element. Also note that I added a test value to one of the inputs to demonstrate the initial state.

$(document).ready(function(){
checkInput();
  })

$('input, select').on('input change',checkInput)

function checkInput(){
$('input, select').each(function(){
      if($(this).val() == ''){
      $(this).addClass('invalid')}else{  
        $(this).removeClass('invalid')}
  })
}
.invalid{background:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test">
<input type="text">

<select>
    <option></option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

<input type="file">