Calling a function after validating a form in Bootstrap

Asked

Viewed 613 times

1

I am trying to do an exercise which consists of displaying values after the user provides the correct data in a form. I tried to use

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

But it only cleans user data instead of calculating function.

Here’s the full code: https://jsfiddle.net/ctanunes/c1nj2vwd/

  • But you want to submit the form or just calculate?

  • just calculate, but wanted the validations also

2 answers

1


There are 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>

That one type="clean" does not exist in HTML specifications. As invalid, the button will work in the default type="submit", submitting the form.

That one novalidate invalidates the required. As its name suggests, it means that the fields do not need to be validated by HTML.

Change the type from 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 ids two two buttons. When using the same name on id of an element within a form and a function, it creates conflict. If you don’t need ids, remove or change name.

In the form.addEventListener('submit', function (event) { I believe that only the preventdefault() is sufficient to prevent the form from being submitted.

In function limpar() you also need to remove the class .was-validated of form.

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>

  • Thank you so much for the explanation! That was it :)

0

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

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

Touch the idof button id="btn_calcular".

Source

  • Unfortunately that doesn’t solve the problem

  • @Catarinanunes, what exactly do you want the calculating function to return?

  • The calculate function changes the values within the Step, Rate and Value boxes.

  • See, the calculate function is working if you make the change in the id, however the element responsible for displaying the return of the calculation is readonly (read only), so you need to hit this logic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.