How to edit HTML table data with jquery

2

I'm creating a registration page where I can only make use of HTML, jquery and css. However, I have difficulties in the function to change the data of the records, whenever I insert a record in the table, the previous one of the one of the bug in the alteation and sends HTML codes. I'm putting the code here and thank you in advance for 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><scripttype="text/javascript" src="http://files.rafaelwendel.com/jquery.js"></script><scripttype="text/javascript" src="http://files.rafaelwendel.com/jquery.maskedinput.js"></script><formname="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>
    
asked by anonymous 18.09.2015 / 21:40

3 answers

1

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

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

One way to fix this is to assign a scope to your seletor , an optimum candidate in your case is the tr to which the inputs belong ... then 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 that I would use would be to bind these events already when loading the page, using an overload of .on with 3 arguments $('<tabela>').on('evento', '<seletor>', callback) , so it would look like this:

$(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 start using 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 lastly, ID must be unique, so when creating an element dynamically, avoid assigning a% static% to it, so make use of a counter, or rather replace id with id .

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()+"'/>");
    
20.04.2016 / 13:45
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()+"'/>");

 }
    
21.09.2015 / 22:01
0

When you use $(".AltBut").bind("click", Editar); it will loop all buttons with the .AltBut class, so it gives the error.

My suggestion is to create a different class for each button "change" with a variable that will increment each time a record is registered:

class="AltBut'+contabotoes+'"

Create the variable contabotoes in the script:

contabotoes = 1;

Delete the line:

$(".AltBut").bind("click", Editar);

Put the Editar() function out of $(document).ready(function(){} and you can even change the line:

var par = $(this).parent().parent(); //tr

by:

var par = $("."+e).closest("tr"); //pega o primeiro TR

So the whole code would look like this:

$(document).ready(function(){

contabotoes = 1;


  $("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'+contabotoes+'" onclick="Editar(this.className)" value="Alterar"/></td> <td><input type="button" class="salBut" value="Salvar"/></td><td><input type="button" class="ExBut" value="Excluir"/></td></tr>');

        contabotoes++;

        $('#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 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();
  };
});

  function Editar(e){

    var par = $("."+e).closest("tr"); //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()+"'/>");
    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()

  }
    
03.01.2016 / 03:24