Calling a function after validating a form in Bootstrap

1

I'm trying to do an exercise that shows values after the user has supplied the correct data in a form. I tried using

<form class="needs-validation" onsubmit="calcular()" novalidate>

But just clears the user data instead of doing the calculate function.

Here is the complete code: link

    
asked by anonymous 14.06.2018 / 01:49

2 answers

1

You have some problems in the code that is preventing it from working. One of them is the button:

<button type="clean" class="btn btn-primary mb-2 mr-3" id="limpar" onclick="limpar()">Limpar</button>

This type="clean" does not exist in HTML specifications. Since it is invalid, the button will work in type="submit" by submitting the form.

This novalidate invalidates required . As the name suggests, the fields do not have to be validated by HTML.

Change the type of the "Clear" button to button :

<button type="button" class="btn btn-primary mb-2 mr-3" id="limpar" onclick="limpar()">Limpar</button>

Also remove the% s with% s two two buttons. By using the same name in the id of an element within a id and a function, it generates conflict. If you do not need form s, remove them or change your name.

In%% I believe that only id is sufficient to prevent the form from being submitted.

In the form.addEventListener('submit', function (event) { function you must also remove the preventdefault() class from limpar() .

Let's see it working:

<!doctype html>
<html lang="en">

<head>
    <title>Ficha6</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <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>
    <div class="container">
        <h1 class="mt-5 pb-3 font-weight-light">Cálculo de Escalão e IRC</h1>

        <form class="needs-validation" onsubmit="calcular()">
            <div class="form-group">
                <label for="nomeEmpresa">Insira o nome da empresa</label>
                <input type="text" class="form-control" id="nomeEmpresa" placeholder="Nome Empresa" required>
                <div class="valid-feedback">
                    Bom nome!
                </div>
            </div>
            <div class="form-group">
                <label for="lucro">Insira o valor do lucro (euros)</label>
                <input type="number" class="form-control" id="lucro" min="0" placeholder="Lucro" required>
                <div class="invalid-feedback">
                    Insira um valor positivo!
                </div>
            </div>
            <div class="form-group">
                <label for="lucro">Escalão</label>
                <input type="text" class="form-control" id="escalao" readonly>
            </div>
            <div class="form-group">
                <label for="lucro">Taxa de IRC</label>
                <input type="text" class="form-control" id="taxa" readonly>
            </div>
            <div class="form-group">
                <label for="lucro">Valor imposto (euros)</label>
                <input type="text" class="form-control" id="imposto" readonly>
            </div>
            <button type="button" class="btn btn-primary mb-2 mr-3" onclick="limpar()">Limpar</button>
            <button type="submit" class="btn btn-primary mb-2 float-right">Calcular</button>
        </form>

    </div>


    <!-- Optional JavaScript -->
    <script>
        var escaloes = ["Escalão 1", "Escalão 2", "Escalão 3"];
        var taxa = ["12,5%", "25,0%", "28,0%"];

        function calcular() {

            var lucro = parseInt(document.getElementById("lucro").value);
            if (lucro < 12500) {

                document.getElementById("escalao").value = escaloes[0];
                document.getElementById("taxa").value = taxa[0];
                var irc = lucro * 0.125;
                document.getElementById("imposto").value = irc;

            } else if (lucro < 2000000) {

                document.getElementById("escalao").value = escaloes[1];
                document.getElementById("taxa").value = taxa[1];
                var irc = lucro * 0.25;
                document.getElementById("imposto").value = irc;

            } else {

                document.getElementById("escalao").value = escaloes[2];
                document.getElementById("taxa").value = taxa[2];
                var irc = lucro * 0.28;
                document.getElementById("imposto").value = irc;

            }
        }
        function limpar() {
           var forms = document.getElementsByClassName('needs-validation');
           // Loop over them and prevent submission
           var validation = Array.prototype.filter.call(forms, function (form) {
                form.classList.remove('was-validated');
           });
            var nada = '';
            document.getElementById("escalao").value = nada;
            document.getElementById("taxa").value = nada;
            document.getElementById("imposto").value = nada;
            document.getElementById("nomeEmpresa").value = nada;
            document.getElementById("lucro").value = nada;

        }
        function verlucropositivo() {
            var lucro = parseInt(document.getElementById("lucro").value);
        }
    </script>

    <script>
            // Example starter JavaScript for disabling form submissions if there are invalid fields
            (function () {
                'use strict';
                window.addEventListener('load', function () {
                    // Fetch all the forms we want to apply custom Bootstrap validation styles to
                    var forms = document.getElementsByClassName('needs-validation');
                    // Loop over them and prevent submission
                    var validation = Array.prototype.filter.call(forms, function (form) {
                        form.addEventListener('submit', function (event) {
                            event.preventDefault();
                            form.classList.add('was-validated');
                        }, false);
                    });
                }, false);
            })();
    </script>

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <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>
</body>

</html>
    
14.06.2018 / 03:05
0
  

When attaching the event handler to the form element, the scope of the event handler is the form, not the window.

     

As the input elements within a form are appended as properties to the form object, where the name is the key, call calculating () the event handler, where the scope is the form, would equal the form.calculate call (), but the form already has an element with that name form.calcular is the submit button, not the compute () function in the global scope.

Touch id of button id="btn_calcular" .

Font

    
14.06.2018 / 02:33