Page does submit even with error in validation

6

Hello,

I'm having problem 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 having the page make submit in that situation (where the return is false )

# botao1 has the following configuration:

<input type="submit" id="botao1" value="Cadastrar">
    
asked by anonymous 23.11.2015 / 20:39

3 answers

2

You can do this as follows:

$("#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);
}
    
23.11.2015 / 20:46
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
    }
});
    
23.11.2015 / 20:46
0

In order for the page not to execute submit when the return of the validar(); function is false use this condition together with the negation operator ! :

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

e is the parameter of the function that receives the event object firing when the button is clicked, so it is necessary to declare this parameter in its function.

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

  

Understand more about the object event here

     

Understand more about the preventDefault(); function here

    
23.11.2015 / 21:02