Page does Submit even with validation error

Asked

Viewed 72 times

6

Hello,

I’m having trouble with a page because it’s doing Submit even when validation returns false.

    $("#botao1").click(function() {

        $.ajax({
            url : 'adicionadaIdeia',
            type : 'POST',
            async : false,
            data : $("#form1").serialize(),
            success : document.getElementById("botao2").click(),
        });
        return false;
    });

    function validar() {
            //Verifica se necessidade tem item selecionado
            if($('input[name=Listanecessidade]:checked').length  == 0){
                alert("Selecione uma necessidade!");
                $('input[name=Listanecessidade]').focus();
                return false;
            }
    }

I wanted to know how I avoid the page to make Ubmit in this situation (where the return is false)

The #boot 1 has the following setting:

<input type="submit" id="botao1" value="Cadastrar">
  • 1

    What HTML element is the #botao1? you probably need to e.preventDefault(); And with submit you mean the ajax or the form is reloading the page?

  • the #boot 1 is an input

  • ... with type= a ?? Please put html to make the question clearer...

  • <input type="Submit" id="boot 1" value="Register">

  • 2

    Okay, then test with $("#botao1").click(function(e) { e.preventDefault(); etc...

  • 1

    Victor, click [Edit] and add to the question.

Show 1 more comment

3 answers

2

You can do it this way:

$("#botao1").click(function(e) {

  e.preventDefault();//Para o envio do submit

  if (validar()) {

    $.ajax({
      url : 'adicionadaIdeia',
      type : 'POST',
      async : false,
      data : $("#form1").serialize(),
      success : function() { alert('Requisição enviada com sucesso.'); },
    });

  } else {
    alert("Selecione uma necessidade!");
    $('input[name=Listanecessidade]').focus();
  }

});

function validar() {
  //Verifica se necessidade tem item selecionado
  return !($('input[name=Listanecessidade]:checked').length  == 0);
}

0

Change your $.ajax:

$.ajax({
    url : 'adicionadaIdeia',
    type : 'POST',
    async : false,
    data : $("#form1").serialize(),
    success : function(data) {
       document.getElementById("botao2").click(),
    },
    error: function(err){
       //Trate o erro
    }
});

0

So that the page does not run Ubmit when function return validar(); for false use this condition together with the negation operator !:

if(!validar()) {
    e.preventDefault();
}

The e is the parameter of the function that receives the object of the event triggering when the click on the button happens, so it is necessary to declare this parameter in its function.

Example: $("#botao1").click(function(e) {...});.

Understand more about the object event here

Learn more about the function preventDefault(); here

Browser other questions tagged

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