FGF-College-Work / Forum

:beer: Espaço dedicado a discussões e tira dúvida sobre disciplinas e conteúdo tecnológico.
MIT License
13 stars 4 forks source link

Desabilitar botão enquanto o form não estiver válido #215

Open marcialwushu opened 4 years ago

marcialwushu commented 4 years ago

https://pt.stackoverflow.com/questions/121521/desabilitar-bot%C3%A3o-enquanto-o-form-n%C3%A3o-estiver-v%C3%A1lido

  $('#btnSalvar').on('click', function (e) {
            var button = $('#btnSalvar');

            button.prop('disabled', true);

            var valid = $("#MyForm").valid();
            console.log(valid);
            if (!valid) {

                e.preventDefault();
                button.prop('disabled', false);
            } else {
                $('#MyForm').submit();
            }
        });
button:disabled {
    background: red;
}
.invalid {
    background: red;
    color: white;
}
.error {
    color: red;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

<form id="MyForm" novalidate="novalidate">
    <div>
        <label for="name">Name:</label>
        <input type="text" name="name" id="name" required="" data-required-message="Name is required." class="valid">
    </div>
    <div>
        <label for="email">Email:</label>
        <input type="email" name="email" id="email" required="" data-required-message="Email is required." data-type-message="You must provide a valid email address." class="valid"><label for="email" generated="true" class="error" style="display: none;">Please enter a valid email address.</label>
    </div>
    <div>
       <button id="btnSalvar">Salvar</button>
    </div>
</form>