How to edit HTML table data with jquery

Asked

Viewed 3,467 times

2

I am creating a registration page where I can only use HTML, jquery and css. Once registered, the information must be in a table below and this table, the data must be able to be changed However, I’m having difficulties in the function to change the data of the records, whenever I insert a record in the table, the previous of the bug in the move and sends HTML code. I am putting the code here and I thank you from now on any help.

$(document).ready(function(){


  $("input.CEP").mask("99.999-999"); 
  $("input.DN").mask("99/99/9999");


  $('#cancelar').on('click', function(){
    $('#nome').val('');
    $('#DN').val('');	
    $('#email').val('');
    $('#CEP').val('');


  });
  $('#registrar').on('click', function(){

    var nomeVal = form1.nome.value;
    var emailVal = form1.email.value;
    var ddnVal = form1.DN.value;
    var cepVal = form1.CEP.value;

    var testCad = 0;

    console.log(nomeVal);



    if(nomeVal != "" && ddnVal != "" && emailVal != "" && cepVal != ""){



      var filtro = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

      if(filtro.test(emailVal))
      {


        $('#tabCrud').append('<tr"><td>'+ nomeVal +'</td> <td>'+ emailVal +'</td><td>'+ ddnVal +'</td><td>'+ cepVal +'</td> <td><input type="button" class="AltBut" value="Alterar"/></td> <td><input type="button" class="salBut" value="Salvar"/></td><td><input type="button" class="ExBut" value="Excluir"/></td></tr>');

        $('#nome').val('');
        $('#DN').val('');	
        $('#email').val('');
        $('#CEP').val('');

        //$('.salBut').hide();


        $(".AltBut").bind("click", Editar);  
        $(".salBut").bind("click", FunSal);
        $(".ExBut").bind("click", Excluir);


        return true;


      } else {
        alert("Este endereço de email não é válido!");
        document.form1.email.focus();
        return false;
      }



    }else{

      alert("Todos os campos são obrigatorios");
    }



  });	



  function Editar(){

    var par = $(this).parent().parent(); //tr
    var tdNome = par.children("td:nth-child(1)");
    var tdEmail = par.children("td:nth-child(2)");
    var tdDN = par.children("td:nth-child(3)");
    var tdCEP = par.children("td:nth-child(4)");




    tdNome.html("<input type ='text' value='"+tdNome.html()+"'/td>");
    tdEmail.html("<input type='text' id='txtEmail' value='"+tdEmail.html()+"'/>");
    tdDN.html("<input type='text'id='txtDN' value='"+tdDN.html()+"'/>");
    tdCEP.html("<input type='text'id='txtDN' value='"+tdCEP.html()+"'/>");


    //$('.salBut').show()

  }


  function FunSal(){
    var par = $(this).parent().parent(); //tr
    var tdNome = par.children("td:nth-child(1)");
    var tdDN = par.children("td:nth-child(2)");
    var tdEmail = par.children("td:nth-child(3)");
    var tdCEP = par.children("td:nth-child(4)");

    tdNome.html(tdNome.children("input[type=text]").val());
    tdDN.html(tdDN.children("input[type=text]").val());
    tdEmail.html(tdEmail.children("input[type=text]").val());
    tdCEP.html(tdCEP.children("input[type=text]").val());
    //$('.AltBut').show();
    //$('.salBut').hide();


  };


  function Excluir(){
    var par = $(this).parent().parent();
    //$('.AltBut').show() //tr
    par.remove();
  };
});
body {background-color: #FFE4B5;}
table.bordasimples {border-collapse: collapse;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://files.rafaelwendel.com/jquery.js"></script>
<script type="text/javascript" src="http://files.rafaelwendel.com/jquery.maskedinput.js"></script>
<form name="form1" action="#" method="post">
  <table boder = '1px' align=center  >
    <caption>CADASTRO</caption>
    <tr>
      <td><label for ="nome">*Nome: </label></td>
      <td><input id="nome" type="text" name = "nome"></td>
      <td><label id="labelNome"></label> </td>
    </tr>
    <tr>
      <td><label for ="Email">*Email: </label></td>
      <td><input type="text" id="email" name = "email"></td>
    </tr>
    <tr>
      <td><label for ="Data de Nascimento">*Data de Nascimento: </label></td>
      <td><input type="text" class="DN" id="DN" name = "DN"></td>
    </tr>
    <tr>
    </tr>
    <tr>
      <td><label for ="CEP">*CEP: </label></td>
      <td><input type="text" id="CEP" class="CEP" name = "CEP"></td>
    </tr>
    <tr>
      <td colspan="2">
        <!--<input type="submit" id="cadastrar" onclick="validar()">-->
        <input type="button" name="registrar" id="registrar" value="registrar">
        <input type="button" name="Cancelar" id="cancelar" value="Cancelar">
      </td>
    </tr>
  </table>
</form>
<div >
  <table id="tabCrud" border ="1px" align=center bordercolor = " #8B8682  " class="bordasimples" bgcolor =" #D2B48C">
    <tr>
      <td>Nome</td>
      <td>e-mail</td>
      <td>Data Nascimento</td>
      <td>CEP</td>
    </tr>
  </table>
</div>

  • ta missing close the TD tag and input on that line > tdNome.html("<input type ='text' value='"+tdNome.html()+"'/td>");

  • 1

    some examples that may help you http://www.jquery-bootgrid.com/Examples

  • @Josevieiraneto I fixed these errors and still continues to send HTML codes for the change input

  • @jgmnhp takes a look at the response I published

2 answers

1

First, the method of .bind('evento', callback) is decrecated, use the .on('evento', callback).

Second point, how are you not setting a scope for your selector every time you make a $("<seletor>").bind('evento', callback); you are attaching a new Eventlistener to the elements returned by this selector, so by adding 3 lines, the first line will have 3 EventListener duplicates associated with it evento.

one way to correct this is to assign a scope to your seletor, an excellent candidate in your case is tr that inputs belong to... so instead of doing:

$(".AltBut").bind("click", Editar);  
$(".salBut").bind("click", FunSal);
$(".ExBut").bind("click", Excluir);

do as follows:

var linha = $('<tr><td>'+ nomeVal +'</td> <td>'+ emailVal +'</td><td>'+ ddnVal +'</td><td>'+ cepVal +'</td> <td><input type="button" class="AltBut" value="Alterar"/></td> <td><input type="button" class="salBut" value="Salvar"/></td><td><input type="button" class="ExBut" value="Excluir"/></td></tr>');

$(".AltBut", linha).on("click", Editar);  
$(".salBut", linha).on("click", FunSal);
$(".ExBut", linha).on("click", Excluir);

$("#tabCrud").append(linha);

the solution I use, would be to bind these events already while loading the paging, using an overload of the .on with 3 arguments $('<tabela>').on('evento', '<seletor>', callback), then it would be this way:

$(function () {

    /* demais codigo aqui */
    function Editar() { /* demais codigo aqui */ };
    function FunSal() { /* demais codigo aqui */ };
    function Excluir() { /* demais codigo aqui */ };
    /* demais codigo aqui */

    $("#tabCrud").on("click", ".AltBut", Editar);  
    $("#tabCrud").on("click", ".salBut", FunSal);
    $("#tabCrud").on("click", ".ExBut", Excluir);
});

this way, the new elements that will be added to the page have already received the associated events.

and some tips to improve your code, avoid repeating your selectors, do them only once, store in a variable and use this variable... then instead of doing so:

$("input.CEP").mask("99.999-999"); 
$("input.DN").mask("99/99/9999");

$('#cancelar').on('click', function(){
    $('#nome').val('');
    $('#DN').val('');   
    $('#email').val('');
    $('#CEP').val('');
});

do as follows:

var input = {};
input.CEP = $("input.CEP");
input.DN= $("input.CEP");

var cancelar = $("#cancelar");
var nome= $("#nome");
var DN= $("#DN");
var email= $("#email");
var CEP= $("#CEP");

input.CEP.mask("99.999-999"); 
input.DN.mask("99/99/9999");

cancelar.on('click', function(){
    nome.val('');
    DN.val(''); 
    email.val('');
    CEP.val('');
});

and finally, ID should be unique, so when creating an element dynamically, avoid assigning a id static to it, then make use of a counter, or rather replace the id for name.

tdNome.html("<input type ='text' name='txtNome' value='"+tdNome.html()+"'/td>");
tdEmail.html("<input type='text' name='txtEmail' value='"+tdEmail.html()+"'/>");
tdDN.html("<input type='text' name='txtDN' value='"+tdDN.html()+"'/>");
tdCEP.html("<input type='text' name='txtDN' value='"+tdCEP.html()+"'/>");

0

Replace your edit function with this

    function Editar(){

       var par = $(this).parent().parent(); //tr
       var tdNome = par.children("td:nth-child(1)");
       var tdEmail = par.children("td:nth-child(2)");
       var tdDN = par.children("td:nth-child(3)");
       var tdCEP = par.children("td:nth-child(4)");

       tdNome.html("<input type ='text' value='"+tdNome.val()+"'</td>");
       tdEmail.html("<input type='text' id='txtEmail' value='"+tdEmail.val()+"'/>");
       tdDN.html("<input type='text'id='txtDN' value='"+tdDN.val()+"'/>");
       tdCEP.html("<input type='text'id='txtDN' value='"+tdCEP.val()+"'/>");

 }

Browser other questions tagged

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