How to keep the data filled in <input> after clicking send the data?

Asked

Viewed 915 times

2

Hello! I have a table with some input fields, which need to be filled in before the user submits it, however, I needed these completed data to remain after it was sent, even after the page was closed. I’m really struggling to implement this logic.

HTML code

<DOCTYPE HTML>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <script src="jquery.min.js"></script>
        <script src="json2.js"></script>
        <script src="jquery.alphanumeric.pack.js"></script>
        <script src="java.js"></script>
        <link rel="stylesheet" type="text/css" href="folha.css" />
    </head>
    <body>
        <center><b><font size="4" color="#FF0000">PEDIDO DE COTAÇÃO</font></b></center><br>
        <table id="dados">
            <thead>
                <tr>
                    <th id="td_titulo"></th>
                    <th>Descrição</th>
                    <th>Unidade</th>
                    <th>Fabricante</th>
                    <th>Cód. Fabricante</th>
                    <th>Outros Códigos</th>
                    <th>Quantidade</th>
                    <th>Valor Unitário</th>
                    <th>Ações</th>
                </tr>
            </thead>
        <tbody>
                <tr>
                    <td class="pedido">5524</td>
                    <td>PRODUTO 1</td>
                    <td>PC</td>
                    <td>FABRICANTE 1</td>
                    <td>SAE014J/010</td>
                    <td id = "colOriginal">12168</td>
                    <td>1</td>
                    <td><input type="text" name="5060" class="valor"/></td>
                    <td colspan="5" style="text-align: center;">
                    <button class="add" onclick="AddTableRow(this)" type="button" 
                            data-toggle="tooltip" 
                            data-placement="top" 
                            title="Adicione uma nova peça similar">+
                    </button>
                    </td>
                </tr>
                <tr>
                    <td class="pedido">5518</td>
                    <td>PRODUTO 2</td>
                    <td>PC</td>
                    <td>FABRICANTE 2</td>
                    <td>SAE100P/000</td>
                    <td id = "colOriginal">34816 / MLSAE100P000 / 31174 / 3701</td>
                    <td>2</td>
                    <td><input type="text" name="3088" class="valor"/></td>
                    <td colspan="5" style="text-align: center;">
                    <button class="add" onclick="AddTableRow(this)" type="button"
                            data-toggle="tooltip" 
                            data-placement="top" 
                            title="Adicione uma nova peça similar">+
                    </button>
                </tr>
            </tbody>
        </table>
        <br><center><b><font size="2">INFORMAÇÕES EXTRAS</font></b><br></center><br>
        Prazo de Entrega (dias): <input type="text" name="prazo" class="iprazo" size="3" maxlength="3"/>
        Frete (R$): <input type="text" name="frete" class="ifrete" size="5" maxlength="9"/>
        <br><br>
        Observação:<br><br>
        <textarea name="obs" rows="4" style="min-width: 100%" class="tobs"></textarea>
        <br>
        <br><center><input type="button" class="Cenviar" value="Enviar" name="" id="00007667"/></center><br>
        <div class="resultado"></div>
        <br><center><b><font size="4" color="#FF0000">29/04/2019 07:13:08</font></b></center><br>
    </body>
</html>

Javascript code

var i,json,pedido,cont,codigo = new Object, linhasDaTabela = new Array(), lPedidos = new Array();

$(document).ready(function() {
    $(".pedido").hide();
    $("#td_titulo").hide();

    $('.valor').numeric({allow:","});

    //codigo.Fornecedor = $(".Cenviar").attr("id");
    //codigo.Cliente = $(".Cenviar").attr("id");

    pedido = "";
    cont = 0;

    for (i=0;i<$(".pedido").length;i++) {
        if (pedido != $(".pedido")[i].innerHTML) {
            lPedidos[cont] = new Object();
            lPedidos[cont].CodPedido = $(".pedido")[i].innerHTML;
            lPedidos[cont].CodFornecedor = $(".Cenviar").attr("id");
            pedido = $(".pedido")[i].innerHTML;
            cont = cont + 1;

        }

    }

    $.ajax({
        type : "POST",
        contentType : "application/json; charset=utf-8",
        url : "buscar.php",
        data : JSON.stringify(lPedidos),
        success : function(data){
            if (data) {
                var JsonArray = JSON.parse(data);
                $.each(JsonArray, function(key,value){



                    for (i=0;i<$(".valor").length;i++) {
                        if ($(".valor")[i].name == value.cod_pecas) {
                            $(".valor")[i].value = value.valor;

                            if (i===0) {
                            if($(".add")[i].click());
                            }


                        }
                    }

                    if ($(".iprazo")[0] !== undefined) {

                        if ($(".iprazo")[0].name == "prazo") {

                            $(".iprazo")[0].value = value.prazoentrega;

                        }

                    }

                    if ($(".ifrete")[0] !== undefined) {

                        if ($(".ifrete")[0].name == "frete") {

                            $(".ifrete")[0].value = value.vlrfrete;

                        }

                    }

                    if ($(".tobs")[0] !== undefined) {
                        if ($(".tobs")[0].name == "obs") {

                            $(".tobs")[0].value = value.obs;

                        }

                    }

                });

            }

        } 

    });

    $(".Cenviar").click(function() { 

    var j = 0;
    var CodPecasTemp = '';
    var bEntrar = false;

    for (i=0;i<$(".valor").length;i++) {

            linhasDaTabela[i] = new Object();
            linhasDaTabela[i].CodFornecedor = $(".Cenviar").attr("id");
            linhasDaTabela[i].CodPedido = $(".pedido")[i].innerHTML;
            linhasDaTabela[i].valor = $(".valor")[i].value;
            linhasDaTabela[i].CodPeca = $(".valor")[i].name;

            bEntrar = CodPecasTemp === $(".valor")[i].name;

            if ($(".fab")[j] !== undefined && bEntrar) {

               linhasDaTabela[i].Fabricante = $(".fab")[j].value;

            } else {
               linhasDaTabela[i].Fabricante = "";
            } 

            if ($(".codFab")[j] !== undefined && bEntrar) {
               linhasDaTabela[i].CodFabricante = $(".codFab")[j].value;
               j++;
            } else {
               linhasDaTabela[i].CodFabricante = "";
            } 

            if ($(".quantidade")[i] !== undefined) {
               linhasDaTabela[i].Quantidade = $(".quantidade")[i].value;
            } else {
               linhasDaTabela[i].Quantidade = "";
            }       

            if ($(".ifrete")[0] === undefined) {
                linhasDaTabela[i].vlrfrete = 0;
            } else {
                linhasDaTabela[i].vlrfrete = $(".ifrete")[0].value;
            }

            if ($(".iprazo")[0] === undefined) {
                linhasDaTabela[i].prazoentrega = 0;
            } else {
                linhasDaTabela[i].prazoentrega = $(".iprazo")[0].value;
            }
            if ($(".tobs")[0] === undefined) {
                linhasDaTabela[i].obs = "";
            } else {
               linhasDaTabela[i].obs = $(".tobs")[0].value; 
            }

            CodPecasTemp = $(".valor")[i].name;

    }

    $.ajax({
        type : "POST",
        contentType : "application/json; charset=utf-8",
        url : "data.php",
        data : JSON.stringify(linhasDaTabela),
        success : function(data) {
                $(".resultado").html('<center>'+data+'</center>');
        }

    });


  });
   (function($) {  
    AddTableRow = function(btn) {
    var newRow = $("<tr>");
    var cols = "";
    var valorName = $(btn).closest("tr").find(".valor").attr("name").trim();
    cols += '<td class="pedido" style="display: none;">&nbsp;</td>'
    cols += '<td class="descricao">&nbsp;</td>';
    cols += '<td class="unidade">&nbsp;</td>';
    cols += '<td><input type="text" class="fab"/></td>';
    cols += '<td><input type="text" class="codFab"/></td>';
    cols += '<td>&nbsp;</td>';
    cols += '<td class="quantidade">&nbsp;</td>';
    cols += '<td><input type="text" name='+valorName+' class="valor"/></td>';
    cols += '<td>';
    cols += '<button class="remover" onclick="RemoveTableRow(this)" type="button" data-toggle="tooltip" title="Clique para remover a linha">-</button>';
    cols += '</td>';

    $(newRow).append(cols);

    $(newRow).insertAfter($(btn).closest('tr'));

    // pega o texto da 1ª coluna
    var codPed = $(btn).closest("tr").find("td:eq(0)").text().trim();
    // pega o texto da 2ª coluna
    var desc = $(btn).closest("tr").find("td:eq(1)").text().trim();
    // pega o texto da 3ª coluna
    var unid = $(btn).closest("tr").find("td:eq(2)").text().trim();
    // pega o texto da 6ª coluna
    var qtde = $(btn).closest("tr").find("td:eq(6)").text().trim();

    $(btn) // botão clicado
    .closest("tr") // linha pai
    .next() // próxima linha
    .find(".descricao") // busca pela classe
    .text(desc) // adiciona o texto
    .end() // volta para o .next()
    .find(".pedido")
    .text(codPed)
    .end()
    .find(".quantidade")
    .text(qtde)
    .end()
    .find(".unidade")
    .text(unid);

    return false;
    };
})(jQuery);

(function($) {    
    RemoveTableRow = function(item) {       
        var tr = $(item).closest('tr'); 

        tr.fadeOut(400, function() {          
        tr.remove();        
      });   

    return false;     
    }   
})(jQuery);

});

All help is welcome, thanks in advance.

  • the value="" attribute is who stores this information, I’ll help you with this.

  • Could use localStorage.

2 answers

4


Can use localStorage to save HTML. O localStorage is a kind of cache generated by Javascript in the browser that stays permanently. Even by closing the browser you can recover the data saved in it.

Put the content you want to save inside a div with an id, for example:

<body>
   <div id="conteudo">
      // CONTEÚDO DA PÁGINA QUE QUER SALVAR
   </div>
</body>

At the beginning of the click event where you submit the data via AJAX, put the code that will adjust the values of inputs and textarea so that they are saved in localStorage in HTML form:

$(".Cenviar").click(function() {

   // percorre cada input e textarea
   $("#conteudo input, #conteudo textarea").each(function(){
      var t = $(this);
      if(t.prop("tagName") == "INPUT"){
         t.attr("value", t.val());
      }else if(t.prop("tagName") == "TEXTAREA"){
         t.html(t.val());
      }
   });

   localStorage.setItem("dados", $("#conteudo").html()); // salva o HTML da div no localStorage

   // resto do código que já existe
});

Now, inside your own $(document).ready(function() { you will check if localStorage exists. If it exists, you will replace the contents of the div #conteudo for what was saved, with the data filled in the fields and everything:

var locSto = localStorage.getItem("dados");
if(locSto) $("#conteudo").html(locSto);

Done. If you want to remove localStorage at some point, just run:

localStorage.clear();
  • Sam, are you sure Localstorage is a cookie? I ask why a cookie is sent to each request to be read on the server, while Localstorage can only be read on the client.

  • Yes, it is a local storage cookie: https://i.stack.Imgur.com/wRi62.png

  • But that’s a nomenclature used by software. In Firefox it is shown separately: https://imgur.com/a/6LPMyS7. What I mean is that conceptually it is not a cookie

  • It may be. As I use Chrome and it treats localStorage as a cookie, I ended up getting used to the name rss... but I changed the names in the reply. Thanks!

  • Not bad.. I thought I had learned something wrong. D

  • Thank you very much, I’ve been stuck in this for a while, it worked here, thank you very much

Show 1 more comment

1

You can use Localstorage.

Put in the Onload from page to page call to a function that loads the information stored in Localstorage:

<body onload="Carregar();">

The function Carry(); takes the information stored in a localstorage and puts it in the input:

function Carregar(){
   document.getElementById("nome").value = localStorage.getItem("nome");
}

Create a button and attach a function that saves the information entered in the input to a localstorage:

<button type="button" onclick="Salvar();">Salvar</button>

The function Save(); picks up what was typed in the input and puts in a localstorage with a id to be used after:

function Salvar(){
    localStorage.setItem("nome",document.getElementById("nome").value);
} 

Follow the full code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body onload="Carregar();">
    <input id="nome"><button type="button" onclick="Salvar();">Salvar</button>

    <script>
        function Salvar(){
            localStorage.setItem("nome",document.getElementById("nome").value);
        }

        function Carregar(){
            document.getElementById("nome").value = localStorage.getItem("nome");
        }
    </script>
</body>
</html>
  • Thank you so much for your help.

Browser other questions tagged

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