Problem with Spring MVC + javascript

Asked

Viewed 427 times

3

I have a problem related to Spring MVC and javascript/Jquery.

Well I have a jsp with a form and I needed to do a test where when clicking a button jquery clears the text of some "input type='Text'".

I even managed to do the test, but every time I click on the button runs the 'Requestmapping' method in the java class.

So, the class method does some queries in database and returns on the screen by 'Modelandview', so if my intention is just to clean the screen controls do not want to run the queries.

Script to clear 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 this my code, summarizing, I want to click on the button, clear the fields without having to execute the 'searchDados' method. When I take off the 'Form' tag it works, but I can’t give back to Spring when I click on a button.

What can I do to fix this?

  • You probably have someone giving a Ubmit to your <form> . Edit your question and put the full source code of Clear Fields()

1 answer

2

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

In the html button add the parameter event in function call limparCampos:

<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 an observation, avoid placing javascript calls on attributes in html. Since you are already using jQuery, the ideal would be the following:

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

Or even:

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

For the function limparCampos already expects an event parameter.

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

Browser other questions tagged

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