Problems with a table

1

Good morning. I am making a table where rows are added and these can be edited. I had a previous problem which was that I only edited the header, and I fixed that problem but another one was generated: I only edit the first row but the second row and later does not edit them. I do not know why this problem occurs; I show you my program so you can understand me better:

$(document).ready(function() {
	$('#bt_add').click(function() {
		  var check = [];
		  $("#tabla").find('.selected').find('td').each(function(){
		    if($.trim($(this).text()) === "")
		      check.push($(this).attr('id'));
		  });
		  if(check.length === 0)
		    agregar();
		  else
		    alert('Registre los Datos de la Fila ');
		});
	
	  $('#bt_del').click(function() {
	    eliminar();
	  });

	  $('#bt_delall').click(function() {
	    eliminarTodasFilas();

	  });


	});
	var cont = 0;
	var id_fila_selected = [];

	function agregar() {
	  cont++;
	  var fila =

	    '<tr class="selected" id="fila' + cont + 'onclick="seleccionar(this.id);"><td>&nbsp;</td>' +

	    '<td><input type="text" id="nombre"  placeholder="Ingresar nombre"></td>' +

	    '<td><input type="text" id="area"  placeholder="Ingresar area"></td>' +

	    '<td><input type="text" id="puesto"  placeholder="Ingresar puesto"></td>' +

	    '<td><input type="text" id="email"  placeholder="Ingresar email" onkeyup="addToTable(event)"></td></tr>';


	  $('#tabla').append(fila);
	  reordenar();
	}

	function addToTable(e) {
	  if (e.keyCode === 13) {
	    e.preventDefault();
	    const row = e.target.parentNode.parentNode;
	    const inputs = row.querySelectorAll('input');
	    const values = [].map.call(inputs, input => input.value);
	    const tds = row.querySelectorAll('td');
	    [].forEach.call(tds, (td, i) => {
	      if (i === 0) { td.textContent = i + 1; }
	      else { td.innerHTML = values[i - 1]; }
	    });
	    reordenar();
	  }
	}

	function seleccionar(id_fila) {
	  if ($('#' + id_fila).hasClass('seleccionada')) {
	    $('#' + id_fila).removeClass('seleccionada');
	  
	    var existe_el_id = id_fila_selected.indexOf(id_fila); 
	    id_fila_selected.splice(existe_el_id, 1);
	  } else {
	    $('#' + id_fila).addClass('seleccionada');
	   
	    id_fila_selected.push(id_fila); 
	  }
	 
	}

	function eliminar() {

	  for (var i = 0; i < id_fila_selected.length; i++) {
	    $('#' + id_fila_selected[i]).remove();
	  }
	  reordenar();
	}

	function reordenar() {
	  var num = 1;
	  $('#tabla tbody tr').each(function() {
	    $(this).find('td').eq(0).text(num);
	    num++;
	  });
	}

	function eliminarTodasFilas() {
	  $('#tabla tr.selected').each(function() {
	    $(this).remove();
	  });
	}
	
	$(function () {        
		  $("td").on("dblclick",function () {					
		      var OriginalContent = $(this).text();
		      $(this).addClass("cellEditing");
		      $(this).html("<input type='text' value='" + OriginalContent + "' />");
		      $(this).children().first().focus();
		      $(this).children().first().keypress(function (e) {
		          if (e.which == 13) {
		              var newContent = $(this).val();
		              $(this).parent().text(newContent);
		              $(this).parent().removeClass("cellEditing");
		              }
		          });
		      $(this).children().first().blur(function(){
		          $(this).parent().text(OriginalContent);
		          $(this).parent().removeClass("cellEditing");
		          });
		      });
		  });
#content {
  position: absolute;
  min-height: 50%;
  width: 80%;
  top: 20%;
  left: 5%;
}

.selected {
  cursor: pointer;
}

.selected:hover {
  background-color: #0585C0;
}

.seleccionada {
  background-color: #0585C0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
 	    <div id="content">
		    <h1> Tabla de Ejemplo </h1>
		    <br>
		 <div align="center" style="width:416px;" >
		    <button id="bt_add" class="btn btn-primary">Agregar</button>
			<button id="bt_del" class="btn btn-primary">Eliminar</button>
		    <button id="bt_delall" class="btn btn-primary">Eliminar todo</button>
			 </div>
		    <table id="tabla" style= "position:absolute;top:150px;left:75px" class="table table-bordered">
		       
		    <thead style="background-color:powderblue;">
		
		  
		<tr>
			<th >Nº</th>
			<th>NOMBRE</th>
			<th>AREA</th>
			<th>PUESTO</th>
			<th>EMAIL</th>
	
			</tr>
	    
	   <tr id=fila'+cont+' onclick="seleccionar(this.id);"><td>&nbsp;</td>
    <td><input type="text" id="nombre"  placeholder="Ingresar nombre"></td>
    <td><input type="text" id="area"  placeholder="Ingresar area"></td>
    <td><input type="text" id="puesto"  placeholder="Ingresar puesto"></td>
  <td><input type="text" id="email"  placeholder="Ingresar email" onkeyup="addToTable(event)"></td></tr>
	   
	    	</thead>
	        </table>
	        </div>


</body>
    
asked by Reinos Ric 20.07.2017 в 17:36
source

1 answer

1

The problem happens because when you add the listeners to the cells they apply only to the cells that exist at that moment in the DOM. When you add new rows, you add those rows on demand, therefore, these rows do not have any associated listener because they have just been created and added to the DOM.

Use event delegation so that, in this way, the listener is listened to in the table and delegated to the cells.

Example

$(document).ready(function() {
  $('#bt_add').click(function() {
    var check = [];
    $("#tabla").find('.selected').find('td').each(function() {
      if ($.trim($(this).text()) === "")
        check.push($(this).attr('id'));
    });
    if (check.length === 0)
      agregar();
    else
      alert('Registre los Datos de la Fila ');
  });

  $('#bt_del').click(function() {
    eliminar();
  });

  $('#bt_delall').click(function() {
    eliminarTodasFilas();

  });


});
var cont = 0;
var id_fila_selected = [];

function agregar() {
  cont++;
  var fila =

    '<tr class="selected" id="fila' + cont + 'onclick="seleccionar(this.id);"><td>&nbsp;</td>' +

    '<td><input type="text" id="nombre"  placeholder="Ingresar nombre"></td>' +

    '<td><input type="text" id="area"  placeholder="Ingresar area"></td>' +

    '<td><input type="text" id="puesto"  placeholder="Ingresar puesto"></td>' +

    '<td><input type="text" id="email"  placeholder="Ingresar email" onkeyup="addToTable(event)"></td></tr>';


  $('#tabla').append(fila);
  reordenar();
}

function addToTable(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    const row = e.target.parentNode.parentNode;
    const inputs = row.querySelectorAll('input');
    const values = [].map.call(inputs, input => input.value);
    const tds = row.querySelectorAll('td');
    [].forEach.call(tds, (td, i) => {
      if (i === 0) {
        td.textContent = i + 1;
      } else {
        td.innerHTML = values[i - 1];
      }
    });
    reordenar();
  }
}

function seleccionar(id_fila) {
  if ($('#' + id_fila).hasClass('seleccionada')) {
    $('#' + id_fila).removeClass('seleccionada');

    var existe_el_id = id_fila_selected.indexOf(id_fila);
    id_fila_selected.splice(existe_el_id, 1);
  } else {
    $('#' + id_fila).addClass('seleccionada');

    id_fila_selected.push(id_fila);
  }

}

function eliminar() {

  for (var i = 0; i < id_fila_selected.length; i++) {
    $('#' + id_fila_selected[i]).remove();
  }
  reordenar();
}

function reordenar() {
  var num = 1;
  $('#tabla tbody tr').each(function() {
    $(this).find('td').eq(0).text(num);
    num++;
  });
}

function eliminarTodasFilas() {
  $('#tabla tr.selected').each(function() {
    $(this).remove();
  });
}

$(function() {
  $("table").on("dblclick", "td", function() {
    var OriginalContent = $(this).text();
    $(this).addClass("cellEditing");
    $(this).html("<input type='text' value='" + OriginalContent + "' />");
    $(this).children().first().focus();
    $(this).children().first().keypress(function(e) {
      if (e.which == 13) {
        var newContent = $(this).val();
        $(this).parent().text(newContent);
        $(this).parent().removeClass("cellEditing");
      }
    });
    $(this).children().first().blur(function() {
      $(this).parent().text(OriginalContent);
      $(this).parent().removeClass("cellEditing");
    });
  });
});
#content {
  position: absolute;
  min-height: 50%;
  width: 80%;
  top: 20%;
  left: 5%;
}

.selected {
  cursor: pointer;
}

.selected:hover {
  background-color: #0585C0;
}

.seleccionada {
  background-color: #0585C0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="content">
    <h1> Tabla de Ejemplo </h1>
    <br>
    <div align="center" style="width:416px;">
      <button id="bt_add" class="btn btn-primary">Agregar</button>
      <button id="bt_del" class="btn btn-primary">Eliminar</button>
      <button id="bt_delall" class="btn btn-primary">Eliminar todo</button>
    </div>
    <table id="tabla" style="position:absolute;top:150px;left:75px" class="table table-bordered">

      <thead style="background-color:powderblue;">


        <tr>
          <th>Nº</th>
          <th>NOMBRE</th>
          <th>AREA</th>
          <th>PUESTO</th>
          <th>EMAIL</th>

        </tr>

               </thead>
    </table>
  </div>


</body>
    
answered by 20.07.2017 / 17:56
source