java - Updating list after insert new items through a JSP form -
in spring project, passing list jsp page controller in way:
mav.addobject("tipos", tipo.listatipos()); mav.addobject("campos", atributo.listakey());
in jsp page, besides display items, can add new items too, demonstrated in code below (both html , jquery):
html
<table class="bordered campos" id="edit_campos"> <thead> <tr> <th>campo</th> <th>#</th> </tr> </thead> <tfoot> <tr> <td> <input type="text" name="nome_campo"> </td> <td> <button type="button" id="incluir_campo" class="btn btn-link">incluir</button> </td> </tr> </tfoot> <c:foreach var="item_key" items="${campos}"> <tr id="linha_${item_key.id}"> <td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td> <td> <button type="button" id="excluir_campo" class="btn btn-link">excluir</button> </td> </tr> </c:foreach> </table>
jquery
$("#incluir_campo").on("click", function () { $.ajax({ type: "get", url: "<c:out value="${pagecontext.request.contextpath}/key/cadastra_campo"/>", data: {nome: $("input[name=nome_campo]").val() } }).done(function(data){ if(data=="yes") { var newrow = $("<tr>"); cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>'; cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">excluir</button> </td>'; newrow.append(cols); $("table.campos").append(newrow); $("input[name=nome_campo]").val(""); } else { alert("erro ao incluir campo"); } }).fail(function(){ alert("falha ao incluir campo"); }); });
but, in current scenario, new lines display no content, due list passed jsp remains same. how can update list passed jsp after insert new item?
look @ these lines:
cols = '<td> <input type="text" name="${item_key.nome}" value="${item_key.nome}"> </td>'; cols += '<td> <button type="button" id="excluir_campo_${item_campo.id}" class="btn btn-link">excluir</button> </td>';
don't use expressions(${}
) in jquery when working dynamically dom elemnts insert new, update dom etc, expressions evaluated when jsp processed/rendered html.
solution be:
after getting new item in controller add list, , return same item response ajax, append exists table. like:
consider controller method returns data in json like:
var data = {"item_key" : {nome : "abc"}, "item_campo" : {id : "1"}};
then in done like:
.done(function(data){ if(data.length != 0) { var $newrow = $("<tr>"); var $newtextbox = $('<input type="text" id="'+data.item_key.nome+'" name="foo">'); var $newbutton = $('<button type="button" id="excluir_campo_'+data.item_campo.id+'" class="btn btn-link">excluir</button>'); $newrow.append($('<td>').append($newtextbox)); $newrow.append($('<td>').append($newbutton)); $("table.campos").append($newrow); $("input[name=nome_campo]").val(""); } else { alert("erro ao incluir campo"); } })
Comments
Post a Comment