Prevent the action of reloading the page by clicking ALERT JS OK

2

I do a very rough check to see if the form is filled, if it is not there is a alert("Preencha todos os campos!"); , the problem is that when I click OK it reloads the page and thus clearing the form.

  • I need the alert OK button not to clear the form.
  • If possible, I want to redirect the fields that are not filled in.

JS

$('#btnCadMed').click(function(){
        var nome = $("#txtNome").val();
        var CRM = $("#txtCRM").val();
        var idt = $("#txtIdentificador").val();
        var esp = $("#txtEspecialidade").val();
        if(nome == "" || CRM == "" || idt == "" || esp == ""){
            alert("Preencha todos os campos!");
        }else{
            $("#txtNome").val("");
            $("#txtCRM").val("");
            $("#txtIdentificador").val("");
            $("#txtEspecialidade").val("");
            alert("Médico cadastrado com sucesso!");
        }
    });

Print the alert

    
asked by anonymous 07.07.2015 / 19:50

2 answers

1

Your button is posting the form, which is why the page is being reloaded.

Do the following, switch to:

$('form').submit(function(){
        var nome = $("#txtNome").val();
        var CRM = $("#txtCRM").val();
        var idt = $("#txtIdentificador").val();
        var esp = $("#txtEspecialidade").val();
        if(nome == "" || CRM == "" || idt == "" || esp == ""){
            alert("Preencha todos os campos!");
            return false;
        }else{
            $("#txtNome").val("");
            $("#txtCRM").val("");
            $("#txtIdentificador").val("");
            $("#txtEspecialidade").val("");
            alert("Médico cadastrado com sucesso!");
           return true
        }
    });

So, it will only post the form if the condition is true.

    
07.07.2015 / 21:20
2

The @vanvan answer is correct and in my opinion it should be used, but only for the purpose of information:

$('#btnCadMed').click(function(e) {
    if(nome == "" || CRM == "" || idt == "" || esp == ""){
        alert("Preencha todos os campos!");
        e.preventDefault();

e.preventDefault() should work as well as return false works on the submit event of the form.

Fiddle

    
07.07.2015 / 22:49