Pass values from a table to a modal dialog (JSP)

Asked

Viewed 2,062 times

1

Good afternoon, you guys! I’m trying to pass values from a table to a modal window, but I’m not getting... I tried something from jquery, but I don’t know what I might be doing wrong... I’ll post the code, which is working, but no changes I made in the attempts...

Exemplo da tabela funcionando

By clicking change, I would like to take the values and move to the dialog.

Thank you all for your help :)

                    <c:if test="${fn:length(lista) > 0 }">
                    <table class="table table-hover">
                        <tr>

                            <th >Código</th>
                            <th>Nome</th>
                            <th>Descrição</th>
                            <th>Medida</th>
                            <th>Fornecedor</th>
                            <th>Quantidade Mínima</th>
                            <th>Quantidade Máxima</th>
                            <th>Estoque</th>
                            <th>Categoria</th>
                            <th>Preço</th>
                            <th></th>
                        </tr>
                        <c:forEach items="${lista }" var="mat">
                            <tr>

                                <td>${mat.codigo }</td>
                                <td>${mat.nome }</td>
                                <td>${mat.descricao }</td>
                                <td>${mat.medida }</td>
                                <td>${mat.fornecedor }</td>
                                <td>${mat.qtd_Min }</td>
                                <td>${mat.qtd_Max }</td>
                                <td>${mat.estoque }</td>
                                <td>${mat.categoria.categoria }</td>
                                <td>${mat.preco }</td>

                                <td><a href="#DialogAlterarMaterial" class="btn btn-xs btn-info" data-toggle="modal">Alterar</a> 
                                    <a href="remover.html?id_material=${mat.id_material }"class="btn btn-xs btn-danger" >Remover</a>
                                </td>
                            </tr>
                        </c:forEach>
                    </table>

                </c:if>

     <!--  ----------------------------------------------Painel para Alteração---------------------------------------------------------------------------- -->

                      <div id="DialogAlterarMaterial" class="modal fade"
                            aria-hidden="true" aria-labelledby="myModalLabel" role="dialog"
                            tabindex="-1" style="display: none;">

                            <div class="modal-dialog" style="width: 800px;">
                                <div class="modal-content">

                                    <div class="modal-header">
                                        <button class="close" aria-hidden="true" data-dismiss="modal"
                                            type="button">×</button>
                                        <h4 class="modal-title">Cadastro de Materiais</h4>
                                    </div>
                                    <div class="modal-body" style="min-height: 500px;">

                                        <form action="alterar.html" method="post">
                                            <div class="form-group" style="width: 80px; float: left;margin-top: 0%">
                                                <label for="codigo">Código</label> <input name="codigo"
                                                    class="form-control" type="text" value="${mat.codigo }">
                                            </div>
                                            <div class="form-group"
                                                style="width: 300px; float: left; margin-top: 9%; margin-left: -10.5%">
                                                <label for="nome">Nome</label> <input name="nome"
                                                    class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 430px; float: left; margin-left: 2%; margin-top: 9%;">
                                                <label for="descricao">Descrição</label> <input
                                                    name="descricao" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 130px; float: left; margin-left: 0%; margin-top: 0%">
                                                <label for="unimed">Unidade de Medida</label> <input
                                                    name="unimed" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 155px; float: left; margin-left: 2%;margin-top: 0%">
                                                <label for="preco">Preço</label> <input name="preco"
                                                    class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 430px; float: left; margin-left: 2%;margin-top: 0%">
                                                <label for="fornecedor">Fornecedor</label> <input
                                                    name="fornecedor" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 85px; float: left; margin-left: 0%;">
                                                <label for="qtdMin">Qtd. Mínima</label> <input
                                                    name="qtd_Min" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 85px; float: left; margin-left: 2%;">
                                                <label for="qtdMax">Qtd. Máxima</label> <input
                                                    name="qtd_Max" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 85px; float: left; margin-left: 2%;">
                                                <label for="estoque">Estoque</label> <input
                                                    name="estoque" class="form-control" type="text">
                                            </div>
                                            <div class="form-group"
                                                style="width: 130px; float: left; margin-left: -38%;margin-top: 10%;">
                                                <label for="categoria">Categoria</label> <select 
                                                    name="categoria" class="form-control" type="text" onchange='CheckCat(this.value);'>
                                                    <option selected disabled hidden>Categoria</option>
                                                    <c:forEach items="${cBean.listarCategoria}" var="cat">
                                                    <option  value="${cat.categoria }">${cat.categoria }</option>



                                                    </c:forEach>
                                                </select>
                                            </div>
                                            <div class="form-group"
                                                style="width: 130px; float: left; margin-left: -19%;display: none; margin-top: 10%" id="Outros">
                                                <label for="catOutros">Outros</label> <input name="catOutros"
                                                    class="form-control" type="text" >
                                            </div>

                                            <div style="width: 30px; margin-top: 25%;float: right;margin-right: 8%">
                                                <button class="btn btn-primary" type="submit">Cadastar</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>




     <!--  --------------------------------------------Fim do Painel para Alteração---------------------------------------------------------------------------- -->

2 answers

1


To solve this problem you can adopt several alternatives, among them:

  • Generate a unique identifier for each <td>
  • Reclaim the fields <td> in order according to <tr> Parent.

I’ll comment a little on the two and give an example code for you to situate.

Option 1 - Generate unique identifier for each <td>

You need to make sure that each row of the column has a unique identifier, so you can use it to distinguish the <td>. In this case I’ll use the field código.

It would look something like this:

<table class="table table-hover">
<tr>
    <th >Código</th>
    <th>Nome</th>
    <th>Descrição</th>
    <th>Medida</th>
    <th>Fornecedor</th>
    <th>Quantidade Mínima</th>
    <th>Quantidade Máxima</th>
    <th>Estoque</th>
    <th>Categoria</th>
    <th>Preço</th>
    <th></th>
</tr>
<c:forEach items="${lista}" var="mat">
    <tr>
        <td id="codigo${mat.codigo}">${mat.codigo }</td>
        <td id="nome${mat.codigo}">${mat.nome }</td>
        <td id="descricao${mat.codigo}">${mat.descricao }</td>
        <td id="medida${mat.codigo}">${mat.medida }</td>
        <td id="fornecedor${mat.codigo}">${mat.fornecedor }</td>
        <td id="qtd_Min${mat.codigo}">${mat.qtd_Min }</td>
        <td id="qtd_Max${mat.codigo}">${mat.qtd_Max }</td>
        <td id="estoque${mat.codigo}">${mat.estoque }</td>
        <td id="categoria${mat.codigo}">${mat.categoria.categoria }</td>
        <td id="preco${mat.codigo}">${mat.preco }</td>
        <td><a href="#DialogAlterarMaterial" class="btn btn-xs btn-info alterar" data-toggle="modal" data-id="${mat.codigo}">Alterar</a>
            <a href="remover.html?id_material=${mat.id_material }"class="btn btn-xs btn-danger" >Remover</a>
        </td>
    </tr>
</c:forEach>

In the end, the html will remain so generated:

<!-- ... -->
<td id="codigo0202">0202</td>
<td id="nome0202">teste</td>
<td id="descricao0202">teste</td>
<!-- ... -->

Then with JQuery you can recover these values through the attribute data-id added on button and thus will have a identifier of each <td>:

$(".alterar").on('click', function(){
   var id = $(this).data('id'); //recuperar qual o id da linha
   //agora vamos usar o id da linha para recuperar cada campo..
   var nome = $('#nome' + id).text(); //vai retornar nome da linha do botão
   var descricao = $('#descricao' + id).text(); //vai retornar descricao da linha do botao
   //..assim por diante..
   //agora voce pode jogar esses valores no seu modal
   //depois de jogar tudo, voce pode exibir seu modal manualmente:
   $("#DialogAlterarMaterial").modal();
});

Option 2 - Recover values according to parent <tr>

The other alternative is to recover the values according to the parent button. The logic is equivalent to the logic explained above, but simpler. You only need this time to add the id from row to tag <tr> which is a container for the entire line.

It would look something like this:

<table class="table table-hover">
    <tr>
        <th >Código</th>
        <th>Nome</th>
        <th>Descrição</th>
        <th>Medida</th>
        <th>Fornecedor</th>
        <th>Quantidade Mínima</th>
        <th>Quantidade Máxima</th>
        <th>Estoque</th>
        <th>Categoria</th>
        <th>Preço</th>
        <th></th>
    </tr>
    <c:forEach items="${lista}" var="mat">
        <tr id="linha${mat.codigo}">
            <td>${mat.codigo }</td>
            <td>${mat.nome }</td>
            <td>${mat.descricao }</td>
            <td>${mat.medida }</td>
            <td>${mat.fornecedor }</td>
            <td>${mat.qtd_Min }</td>
            <td>${mat.qtd_Max }</td>
            <td>${mat.estoque }</td>
            <td>${mat.categoria.categoria }</td>
            <td>${mat.preco }</td>
            <td><a href="#DialogAlterarMaterial" class="btn btn-xs btn-info alterar" data-toggle="modal" data-id="${mat.codigo}">Alterar</a>
                <a href="remover.html?id_material=${mat.id_material }"class="btn btn-xs btn-danger" >Remover</a>
            </td>
        </tr>
    </c:forEach>
</table>

What is interesting to note in this code is the line: <tr id="linha${mat.codigo}">... You are no longer leaving every tag <td> unique in the table, but yes, each parent or container of <td> that is, the <tr>.

So you can recover the values of each td using JQuery as follows:

$(".alterar").on('click', function(){
       var id = $(this).data('id'); //recuperar qual o id da linha
       //agora vamos usar o id para recuperar a linha inteira ou o <tr>
       var linha = $('#linha' + id); //temos o <tr> atribuidos a variavel linha
       var nome = $(linha[1]).text(); //vai retornar nome da linha do botão
       var descricao = $(linha[2]).text();.text(); //vai retornar descricao da linha do botao
       //..assim por diante..
       //agora voce pode jogar esses valores no seu modal
       //depois de jogar tudo, voce pode exibir seu modal manualmente:
       $("#DialogAlterarMaterial").modal();
    });

In the code above, you may notice that the line will contain an object JQuery who owns all the <td>'s within it in the form of indexes of a Array. Just access these indexes to retrieve each field you need to assemble your modal.

I hope I’ve helped.

  • Man, thanks for the answer, it’s great, very well explained. I just don’t understand what I’m going to call these values in modal... can you explain it to me, please? I’ve tried a few ways here and nothing’s showing up...

  • Ahhhh, I’m using the first option, and it’s all cool with the generated html, it’s happening the way you said.

  • Within each input of the modal you put a id, example: <input name="descricao" class="form-control" type="text" id="mdescricao">. Dai you add the recovered value on JQuery inside the value field of this input, example: var descricao = $('#descricao' + id).text(); $("#mdescricao").val(descricao);.

  • Thanks friend, I will test as soon as q arrive at ksa and warning :)

  • 1

    Friend, thank you! It worked perfectly!!! I was a few days ago breaking my head with this... I didn’t think anything worked... Thank you :)

0

Change this line in the code by adding the .children() that will be round

Before:

var linha = $('#linha' + id); //temos o <tr> atribuidos a variavel linha

Afterward:

var linha = $('#linha' + id).children(); //temos o <tr> atribuidos a variavel linha

Browser other questions tagged

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