Graphenous
Graphenous

Reputation: 57

Trying to show a div if the input value of a form field is empty, using jQuery

Hello I am working with bootstrap trying to show a warning-div when login/password not filled but it seems like it shows but hide again so not showing at all, here is the code:

<head>
    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script language="javaScript">  
        var namePattern = "^[a-z A-Z]{4,30}$";
        $(document).ready(function(){
            $("#bEnviar").click(function(){
                var login = $("#login").val();
                var password = $("#password").val();
                if( login=="" ){
                    $("#login").css("display","block");
                }
                if( password="" ){
                }
            });
        });
    </script>
</head>
<body>
    <form action="">
        <div class="form-group col-md-12">
            <label for="login" class="col-form-label">Login</label>
            <input type="text" id="login" class="form-control" placeholder="Login">             
            <div id="login" class="alert alert-danger d-none" role="alert-danger">
                Inserte nombre de usuario
            </div>
        </div>
        <div class="form-group col-md-12">
            <label for="password" class="col-form-label">Password</label>
            <input type="password" id="password" class="form-control" placeholder="Password">
            <div id="pass" class="alert alert-danger d-none" role="alert-danger">
                Inserte password
            </div>
        </div>
        <div class="form-group col-md-12"> 
            <button type='submit' id="bEnviar" class="btn btn-primary">Ingresar</button>
        </div>
    </form>
</body>

Javascript is working fine cus i tried an alert and when i press submit button it shows.

Thanks in advance!

Upvotes: 0

Views: 1141

Answers (5)

Chukwuemeka Inya
Chukwuemeka Inya

Reputation: 2671

The main reason why it is appearing and then disappearing is because your form is getting submitted by default. You need to prevent that by passing the event to the click function and then calling event.preventDefault(), before trying to change the display style.

Another point to note is the use of 1 id for multiple elements. IDs are unique, thus 1 ID per element. So, you should also rename your error divs perhaps to login_error and password_error.

So, you jquery should look thus:

    $(document).ready(function () {
        $("#bEnviar").click(function (e) {
            e.preventDefault();    //Prevent forms default behaviour
            var login = $("#login").val();
            var password = $("#password").val();

            // If the login value is not set
            if (!login) {
                $("#login_error").css("display", "block"); // This overrides d-none and makes it display
            }
            // If the password value is not set
            if (!password) {
                $("#password_error").css("display", "block");
            }
        });

    });

Since the action attribute in your form is empty, you can do away with it and just have <form></form>

I assumed that d-none in your html translates to display-none and sets the display of the error divs to none. If not, you have to first set the error divs to display none in your css before your script fires and sets them to display block. The CSS below should do that:

    <style>
        .form-group #password_error,
        .form-group #login_error {
            display: none;
        }
    </style>

Upvotes: 0

nmak18
nmak18

Reputation: 1169

Hi the page is reloading as the form is getting submitted. You need to prevent the form from getting submitted in case of error.

You can either use event.preventDefault() or return false

Also, the ID needs to be unique for each element. You are using the "login" as id for both the message div and the input element.

Hope the below code snippet helps.

var namePattern = "^[a-z A-Z]{4,30}$";

$(document).ready(function() {
  $("#bEnviar").click(function(event) {
    debugger;
    var login = $("#login").val();
    var password = $("#password").val();

    if (login === "") {
      $("#login-err").removeClass("d-none");
      // use prevent default or return false
      event.preventDefault()
      return false;
    }
    if (password === "") {
      $("#password-err").removeClass("d-none");
      // use prevent default or return false
      event.preventDefault()
      return false;
    }
  });

});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

<form action="">
  <div class="form-group col-md-12">
    <label for="login" class="col-form-label">Login</label>
    <input type="text" id="login" class="form-control" placeholder="Login">
    <div id="login-err" class="alert alert-danger d-none" role="alert-danger">
      Inserte nombre de usuario
    </div>
  </div>

  <div class="form-group col-md-12">
    <label for="password" class="col-form-label">Password</label>
    <input type="password" id="password" class="form-control" placeholder="Password">
    <div id="password-err" class="alert alert-danger d-none" role="alert-danger">
      Inserte password
    </div>
  </div>
  <div class="form-group col-md-12">
    <button type='submit' id="bEnviar" class="btn btn-primary">Ingresar</button>
  </div>

</form>

Upvotes: 0

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You have 3 main errors in your code:

  1. There are 2 elements with the same id login.

  2. If you want to check your input before submit, you shouldn't use type="submit" because it will submit the form anyway when you click the button. Use type="button" if use want to check your input first.

  3. Class d-none has css display: none!important; so you need to remove it if you want the div to display.

Here's the code after fixed these errors:

var namePattern = "^[a-z A-Z]{4,30}$";

    $(document).ready(function(){
        $("#bEnviar").click(function(){
            var login = $("#login").val();
            var password = $("#password").val();

            if(!login) {
                $("#login_error").removeClass("d-none");
            } else $("#login_error").addClass("d-none");
            if(!password) {
                $("#pass").removeClass("d-none");
            } else $("#pass").addClass("d-none");
            
            if (login && password) {
              // Submit form
            }
        });

    });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<form action="">
            <div class="form-group col-md-12">
                <label for="login" class="col-form-label">Login</label>
                <input type="text" id="login" class="form-control" placeholder="Login">             
                <div id="login_error" class="alert alert-danger d-none" role="alert-danger">
                    Inserte nombre de usuario
                </div>
            </div>

            <div class="form-group col-md-12">
                <label for="password" class="col-form-label">Password</label>
                <input type="password" id="password" class="form-control" placeholder="Password">
                <div id="pass" class="alert alert-danger d-none" role="alert-danger">
                    Inserte password
                </div>
            </div>
            <div class="form-group col-md-12"> 
                <button type='button' id="bEnviar" class="btn btn-primary">Ingresar</button>
            </div>

        </form>

Upvotes: 2

BJ Anderson
BJ Anderson

Reputation: 1256

There are 2 main things you need to fix.

First make the form action point to the same page. When action="" it reloads the page, when action="#" it points to something within the page.

second, your logic for if (password = "") should be if (password === "") notice assignment vs. comparison.

Then you just need to remove the d-none class from your id=pass div

Here's a working version of your code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
  <form action="#">
    <div class="form-group col-md-12">
        <label for="login" class="col-form-label">Login</label>
        <input type="text" id="login" class="form-control" placeholder="Login">
        <div id="login" class="alert alert-danger d-none" role="alert-danger">
            Inserte nombre de usuario
        </div>
    </div>

    <div class="form-group col-md-12">
        <label for="password" class="col-form-label">Password</label>
        <input type="password" id="password" class="form-control" placeholder="Password">
        <div id="pass" class="alert alert-danger d-none" role="alert-danger">
            Inserte password
        </div>
    </div>
    <div class="form-group col-md-12">
        <button type='submit' id="bEnviar" class="btn btn-primary">Ingresar</button>
    </div>

</form>

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

  <script>

      var namePattern = "^[a-z A-Z]{4,30}$";

      $(document).ready(function(){
          $("#bEnviar").click(function(){
            console.log('clicked #bEnviar');
              var login = $("#login").val();
              var password = $("#password").val();

              if( login === "" ){
                  $("#login").css("display","block");

              }
              if( password === "" ){
                $("#pass").removeClass('d-none');

              }
          });

      });
  </script>
</body>
</html>

Upvotes: 0

Akhilesh
Akhilesh

Reputation: 968

change this

<div id="login_error" class="alert alert-danger d-none" role="alert-danger">

and then in javascript you have to use

$("#login_error").css("display","block");

as two elements can not have same id. You are using login id in input as well as in div which will not work.

Upvotes: 0

Related Questions