Problem with Spring MVC + javascript

3

I'm having an issue with Spring MVC and jQuery.

I have a jsp with a 'form' and I needed to do a test where when I click on a button, jquery clears the texts of some "input type = 'Text'".

I even managed to test, but every time I click the button, the 'RequestMapping' method is executed in the class in Java.

So, the class method does a database query and returns on the screen through 'ModelAndView', so if my intention is just to clear the controls on the screen I do not want to be running queries.

  

Script to clean fields

    function limparCampos()
    {
         $(".cmpTexto").val("");
    }
  

Html Code

    <form action="UCC001.htm" method="post">
       <table>
          <tr>
             <td>Nome:</td>
             <td><input type="text" class="cmpTexto" value="${cad.nome}" name="nome"/></td>
          </tr>
          <tr>
             <td>Endereço:</td>
             <td><input type="text" class="cmpTexto" value="${cad.endereco}"   name="endereco"/></td>
          </tr>
       </table>
       <input type="button" onclick="limparCampos()" value="Limpar Campos">
    </form>
  

Class Method

    @RequestMapping("/UCC001")
    public ModelAndView buscaDados(Cadastro cadastro)
    {
         Cadastro cad = new Cadastro();
         cadastro = retCadastro(); //Retorna dados do banco de dados
         ModelAndView mav = new ModelAndView("cadastro");
         mav.AddObject("cad", cadastro);
         return mav;
    }

More or less this is how my code, in short, I want to click on the button, clear the fields without having to execute the method 'searchdata'. When I take the 'Form' tag it works, but I can not return Spring when I click a button.

What can I do to resolve this?

    
asked by anonymous 30.03.2015 / 16:15

1 answer

1

I believe that the problem can be solved by preventing the default behavior of the button, which in the case is to send the form. This can be resolved as follows:

In the html of the button add the parameter event to the call of the limparCampos function:

<input type="button" onclick="limparCampos(event)" value="Limpar Campos">

In function limparCampos :

function limparCampos (e) {
  e.preventDefault(); // previne que o comportamento padrão do navegador seja executado   
  $('.cmpTexto').val('');
}

Just as a remark, avoid putting javascript calls into attributes in html. As you are already using jQuery, the ideal would be as follows:

$('#idDoBotao').on('click', function (e) {
  limparCampos(e);
});

Or even:

$('#idDoBotao').on('click', limparCampos);

Because the limparCampos function already expects an event parameter.

If you use this way, remember to put the script above the body closing tag.

    
07.04.2015 / 20:44