How can I implement the has-error class as it appears in the image by jquery

1

$(document).ready(function() {
    $("button").on("click", function() {
        
        //Variables para evaluar el ingreso de datos
        var username = ($('#username').val());
        var password = ($('#password').val());
        var condiciones = $("#terms").is(":checked");
      
        //Validar si se ingresaron los datos
        if (!username) {
           $('.form-group').addClass('has-error');
            alert("Debe de ingresar un usuario");
             return false;
        } else {
           $('.form-group').removeClass('has-error'); 
        }
      
        if (!password) {
           $('.form-group').addClass('has-error');
            alert("Debe de ingresar una clave");
             return false;
        } else {
           $('.form-group').removeClass('has-error'); 
        }
        
        if ((password).length < 6) {
           $('.form-group').addClass('has-error');
            alert("Debe de ingresar una clave mayor a 5 caracteres");
             return false;
        } else {
           $('.form-group').removeClass('has-error'); 
        }
        
        if ((password).length > 40) {
           $('.form-group').addClass('has-error');
            alert("Debe de ingresar una clave menor a 40 caracteres");
             return false;
        } else {
           $('.form-group').removeClass('has-error'); 
        }
      
        if (!condiciones) {
           $('#terms').addClass('has-error');
            alert("Debe aceptar las condiciones");
            return false;
        } else {
           $('#terms').removeClass('has-error');
        }

    });
});
.action {
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Formulario de Registro</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div class="col-sm-6 col-sm-offset-3">
      <h1>Formulario de Registro</h1>
      <form>
        <div class="form-group">
          <label class="control-label" for="username">Usuario:</label>
          <input type="text" class="form-control input-lg" id="username" placeholder="Ingresa un usuario">
          <p class="help-block"></p>
        </div>
        <div class="form-group">
          <label class="control-label" for="password">Contraseña</label>
          <input type="password" class="form-control input-lg" id="password" placeholder="Ingresa una contraseña">
          <p class="help-block"></p>
        </div>
        <div class="checkbox terms-checkbox">
          <label>
            <input type="checkbox" id="terms"> Acepto los términos y condiciones
          </label>
        </div>
        <div class="action text-right">
          <button type="submit" class="btn btn-primary btn-block btn-lg">Registrarse</button>
        </div>
      </form>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>

But I am adding all the has-error class to all the .form-group, I do not know how to add it only to the element that has the error and I must add an error message in the index.hrml file, for now I show it in an alert.

    
asked by García Henry 13.05.2018 в 10:16
source

1 answer

1

In order to treat each field separately you can not use a class that is applied to all the elements. Using the parent () method of jQuery I have referred to each element of the html individually.

$(document).ready(function() {
    $("button").on("click", function() {

        //Variables para evaluar el ingreso de datos
        var username = ($('#username').val());
        var password = ($('#password').val());
        var condiciones = $("#terms").is(":checked");

        //Validar si se ingresaron los datos
        if (!username) {
           $('#username').parent().addClass('has-error');
           $('#username').parent().find('.help-block').html('Debe de ingresar un usuario');
           return false;
        } else 
           $('#username').parent().removeClass('has-error');

        if (!password) {
           $('#password').parent().addClass('has-error');
           $('#password').parent().find('.help-block').html('Debe de ingresar una clave');
           return false;
        } else
           $('#password').parent().removeClass('has-error');

        if ((password).length < 6) {
           $('#password').parent().addClass('has-error');
           $('#password').parent().find('.help-block').html('Debe de ingresar una clave mayor a 5 caracteres.');
           return false;
        } else
           $('#password').parent().removeClass('has-error');

        if ((password).length > 40) {
           $('#password').parent().addClass('has-error');
           $('#password').parent().find('.help-block').html('Debe de ingresar una clave menor a 40 caracteres.');
           return false;
        } else
           $('#password').parent().removeClass('has-error');

        if (!condiciones) {
           $('.checkbox').addClass('has-error');
           $('.checkbox').find('.help-block').html('Debe aceptar las condiciones');
            return false;
        } else
           $('.checkbox').removeClass('has-error');
    });
});
.action {
  margin-top: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Formulario de Registro</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <div class="col-sm-6 col-sm-offset-3">
      <h1>Formulario de Registro</h1>
      <form>
        <div class="form-group">
          <label class="control-label" for="username">Usuario:</label>
          <input type="text" class="form-control input-lg" id="username" placeholder="Ingresa un usuario">
          <p class="help-block"></p>
        </div>
        <div class="form-group">
          <label class="control-label" for="password">Contraseña</label>
          <input type="password" class="form-control input-lg" id="password" placeholder="Ingresa una contraseña">
          <p class="help-block"></p>
        </div>
        <div class="checkbox terms-checkbox">
          <label>
            <input type="checkbox" id="terms"> Acepto los términos y condiciones
          </label>
          <p class="help-block"></p>
        </div>
        <div class="action text-right">
          <button type="submit" class="btn btn-primary btn-block btn-lg">Registrarse</button>
        </div>
      </form>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script type="text/javascript" src="app.js"></script>
</body>
</html>
    
answered by 13.05.2018 в 10:35