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

4

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
source

2 answers

0

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", "");
  }
  else{
    $(elemento).css("background-color", "blue");
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <label for="example">Ingreso Texto</label>
  <input type="text" onchange="cambio(this)" id="example" name="example"/>
</body>
    
answered by 30.05.2016 / 16:31
source
3

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:

$(function(){
  $('#search-form :input')
    .change(function(){
      var $input = $(this);
      if ($input.val() === '')
      {
        $input.removeClass('filledInputs');
      }
      else
      {
        $input.addClass('filledInputs');
      }
    });
});
.filledInputs{
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="search-form">
  <input type="text" /> <br /><br />
  <textarea cols="20" rows="4"></textarea> <br /><br />
  <select>
    <option value=""></option>
    <option value="1">Uno</option>
    <option value="2">Dos</option>
    <option value="3">Tres</option>
    <option value="4">Cuatro</option>
  </select>
</form>
    
answered by 30.05.2016 в 16:24