Show modal of Bootstrap with JS

0

The problem I really do not know where it comes from, and it's quite simple, but I do not know how to solve it, the issue is that I have a form that is to be able to enter X site as a user, then it has its respective field of user and password the topic is super simple, if the user is empty, he must skip the modal to indicate to the user that he has an empty field and he must fill it out, the issue is that when I reload and try the script, the first attempt does not work, but the second attempt and all those that precede it if it works and I do not know why it happens

JS Code

window.addEventListener('load', () => {
    var form = document.getElementById("form");
    var user = document.getElementById("user").value;
    var pass = document.getElementById("pass").value;
    
    form.addEventListener('submit', () => {
        alert("Tomo los datos" + form);
        if (user == "") {
            $('#view_error').modal('show');
        } else {
            $('#view_loged').modal('show');
            //alert("logeado");
        }
    });
});


Código de HTML
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Display modal</title>
    <script src="js/modal.js"></script>
    <link rel="stylesheet" href="css/Login-Form-Dark.css">
    <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="css/sett.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
</head>

<body>
    <!-- Inicio modal Error -->
    <div class="modal fade" id="view_error" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalCenterTitle">Error al inciar sesión</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                </div>
            </div>
        </div>
    </div>
    <!-- Cierre Modal Error -->
    <div class="login-dark">
        <form action="#" id="form">
            <h2 class="sr-only">Login Form</h2>
            <div class="illustration"><i class="icon ion-ios-locked-outline"></i></div>
            <div class="form-group"><input class="form-control" type="text" name="user" id="user" placeholder="Usuario"></div>
            <div class="form-group"><input class="form-control" type="password" name="pass" id="pass" placeholder="Contraseña"></div>
            <div class="form-group"><button class="btn btn-primary btn-block" type="submit" data-toggle="modal" data-target="#view_error">Log In</button></div><a href="#" class="forgot">Forgot your email or password?</a>
        </form>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script>
</body>

</html>
 I hope you can help me, I will continue searching, greetings and have a good morning     
asked by Víctor 10.10.2018 в 14:18
source

2 answers

1

Grab your code and put it to work as you need it, the only change you should do is tell the submit event to prevent it from doing what it always does by default which is to send the form and refresh the page, for it to the event submit you pass the parameters which obtains all the characteristics of the event itself in this case e and then you tell it to prevent its behavior with the function preventDefault() , remaining as e.preventDefault(); , like this:

window.addEventListener('load', () => {
    var form = document.getElementById("form");
    var user = document.getElementById("user").value;
    var pass = document.getElementById("pass").value;
    
    form.addEventListener('submit', (e) => {
    
      e.preventDefault();
      alert("Tomo los datos" + form);
      if (user == "") {
        $('#view_error').modal('show');
      } else {
        $('#view_loged').modal('show');
      }
      
    });
});
.container{
  margin:10px;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<!-- Inicio modal Error -->
<div class="modal fade" id="view_error" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalCenterTitle">Error al inciar sesión</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
       Error
      </div>
      <div class="modal-footer"></div>
    </div>
  </div>
</div>
<!-- Cierre Modal Error -->

<div class="container">
  <div class="login-dark">
    <form action="#" id="form">
      <h2 class="sr-only">Login Form</h2>
      <div class="illustration">
        <i class="icon ion-ios-locked-outline"></i>
      </div>
      <div class="form-group">
        <input class="form-control" type="text" name="user" id="user" placeholder="Usuario">
      </div>
      <div class="form-group">
        <input class="form-control" type="password" name="pass" id="pass" placeholder="Contraseña">
      </div>
      <div class="form-group">
        <button class="btn btn-primary btn-block" type="submit" data-toggle="modal" data-target="#view_error">Log In</button>
      </div>
      <a href="#" class="forgot">Forgot your email or password?</a>
    </form>
  </div>
</div>

<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.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
    
answered by 10.10.2018 в 16:43
0

Good morning, have not you tried using the native validation of html5 for empty fields? I mention it because in the code that you put, at the moment of clicking the button, you try to show me the modal but I reload the page, in any case, you can pick up the event submit of form to avoid recharging the page.

Try the following:

$("#form").submit(function(e){
       //aqui pones el código para validar los campos vacíos
    
    //esto te sirve para, de cierta manera, cancelar el envío de datos del form al action que especificaste.
       e.preventDefault();
       return false;
    });

I hope you solve your problem.

    
answered by 10.10.2018 в 14:42