Change background color of an input when it is not empty [jQuery]


Good people.

I am trying to fill in an input itself change its background-color , this would have to be done dynamically, without having to click on a button or reload the page. I tried this, but it does not work:

function ActiveInputs() {
var gg = $('#search-form').find('input:text,select, textarea').val();

$(gg).on('blur', function () {

    if ($(this).val() != '') {
        $(this).css('background-color', 'red');

Does someone lend me a hand?

asked by Andromeda 30.05.2016 в 15:59

2 answers


You could create a function to modify the css with jquery and execute directly through the onchange () event, for example:

function cambio(elemento){
  if ($(elemento).val() === "") {
    $(elemento).css("background-color", "");
    $(elemento).css("background-color", "blue");
<script src=""></script>
  <label for="example">Ingreso Texto</label>
  <input type="text" onchange="cambio(this)" id="example" name="example"/>
answered by 30.05.2016 / 16:31

You can use the selector: input to catch all the elements of the form. In the change event you check if it has value and, depending on whether the value is empty or not, you assign the class css to change the background:

  $('#search-form :input')
      var $input = $(this);
      if ($input.val() === '')
  background-color: red;
<script src=""></script>
<form id="search-form">
  <input type="text" /> <br /><br />
  <textarea cols="20" rows="4"></textarea> <br /><br />
    <option value=""></option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
    <option value="4">Cuatro</option>
answered by 30.05.2016 в 16:24