Class css is not applied when there is an input in focus with jquery

0

I have an input I am using bootstrap 3 for css

<form>
 <div class="row">
  <div class="form-group col-md-6">
    <label>Número de Filas:</label>
    <input type="text" id="no_filasVal" class="form-control">            
  </div>
 </div>
</form>

And I have this jquery code:

$(document).ready(function() {
    $("input").focus(function() {
       $(this).toggleClass("error");
    });
});

Class "error" css:

.error { border-color: #FF0000; }

The question here is because when I put in focus the input does not apply the css class? It applies once that input is not in focus.

    
asked by Jorge Alonso 05.12.2018 в 21:33
source

2 answers

0

You need the event when the focus of the input is removed, the blur :

$("input").focus(function() {
  $(this).toggleClass("error");
});
$("input").blur(function() {
  $(this).toggleClass("error");
});
.error {
  border-color: #FF0000 !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="row">
    <div class="form-group col-md-6">
      <label>Número de Filas:</label>
      <input type="text" id="no_filasVal" class="form-control">
    </div>
  </div>
</form>
    
answered by 05.12.2018 / 21:45
source
0

If what you want is that when you receive the focus (select the input) it is marked red, you do not need JavaScript, add this:

#no_filasVal:focus { border-color: #FF0000 }

I would actually create a utilitarian class called .red-on-focus and ready

I hope it helps you

    
answered by 07.12.2018 в 03:54