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

Asked

Viewed 4,212 times

2

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

  • I need the Alert OK button not to clear the form.
  • If possible I want you to mark in red 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 by Alert inserir a descrição da imagem aqui

  • 1

    Already tried to use a false Return ??

2 answers

2

The @Ivanteles response is correct and in my opinion it should be used, but only for information purposes:

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

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

Fiddle

  • In my opinion this is the right answer. e.preventDefault(); is semantically more correct.

  • @Sergio, yes I agree. I meant that using the event in the form would be more correct than the button itself. Perhaps by combining the two answers he would have the ideal.

1


Your button is posting the form due to which it is being reloaded to the page.

Tell you what, 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
        }
    });

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

Browser other questions tagged

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