Do not validate a row with empty fields

0

I have a problem with the same program that generates, deletes and adds rows within a table, but what I want to do is that when the user does not enter one or any data inside the table, I get a alert that says : "you have not entered the column name please enter it" and also do not add the row with the empty field, the only thing that my program does is not add one more row when it has one already open, I hope you understand my problem. I show you my code:

$(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('No puedo agregar mas de una fila, por favor llene los campos');;
	  });
	  $('#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"></td>' +

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

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

	    '<td><input type="text" id="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');
	    // borrar también el id del array de filas seleccionadas
	    var existe_el_id = id_fila_selected.indexOf(id_fila); 
	    id_fila_selected.splice(existe_el_id, 1);
	  } else {
	    $('#' + id_fila).addClass('seleccionada');
	    // agregar id sólo si se hizo click
	    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://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/css/tether.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

  <label> Tabla de Ejemplo </label>
  <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>
		
<thead>
  <tr>
    <th>Nº</th>
    <th>NOMBRE</th>
    <th>AREA</th>
    <th>PUESTO</th>
    <th>EMAIL</th>
  </tr>
</thead>
  </table>
</div>
    
asked by Reinos Ric 20.07.2017 в 22:29
source

2 answers

0

I just solved my problem, this is my answer:

$(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('No puedo agregar mas de una fila, por favor llene los campos');;
  });



  $('#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"></td>' +

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

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

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


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


function addToTable(e) {
	
  if (e.keyCode === 13) {
    e.preventDefault();
    if($("#nombre").val() == ""){
  		  alert("Ingrese el nombre del usuario");
  		return false;
  	  }else if($("#area").val() == ""){
	 		  alert("Ingrese el nombre de la area");
	 		 return false;
  	  }else if($("#puesto").val() == ""){
	 		  alert("Ingrese el nombre del puesto");
	 		 return false;
  	  }else if($("#email").val() == ""){
	 		  alert("Ingrese su correo electronico");
	 		 return false;
  	  }
    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://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/css/tether.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet"/>

  <label> Tabla de Ejemplo </label>
  <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>
		
<thead>
  <tr>
    <th>Nº</th>
    <th>NOMBRE</th>
    <th>AREA</th>
    <th>PUESTO</th>
    <th>EMAIL</th>
  </tr>
</thead>
  </table>
</div>
    
answered by 21.07.2017 / 00:18
source
1

You have to filter which field is empty for example and if it is empty, take the error with the name field and do not execute the action you want to run only if everything is ok. For example I have done it in the following way:

$(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('No puedo agregar mas de una fila, por favor llene los campos');;
	  });
	  $('#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"></td>' +

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

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

	    '<td><input type="text" id="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');
		console.log(inputs);
	    //const values = [].map.call(inputs, input => input.value);
		const values = [];
		let valido = [].every.call(inputs, input => {
			if (input.value.trim() === "") {
				alert("Inserta el campo "+input.id+". Si no lo ha hecho, ingreselo.");
				return false;
			}
			else {
				values.push(input.value);
				return true;
			}
		});
			
		
		
		if(valido) {
			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');
	    // borrar también el id del array de filas seleccionadas
	    var existe_el_id = id_fila_selected.indexOf(id_fila); 
	    id_fila_selected.splice(existe_el_id, 1);
	  } else {
	    $('#' + id_fila).addClass('seleccionada');
	    // agregar id sólo si se hizo click
	    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>
<div id="content">
  <label> Tabla de Ejemplo </label>
  <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>
		
<thead>
  <tr>
    <th>Nº</th>
    <th>NOMBRE</th>
    <th>AREA</th>
    <th>PUESTO</th>
    <th>EMAIL</th>
  </tr>
</thead>
  </table>
</div>

* This is the important part that you must change.

'the method every what it does is that depending on a callback that returns true or false determines if all the elements of an array meet a condition, in this case, when it reaches a size that returns false because it is a field empty, that is, if the string is empty, it returns 'false' and first shows the error message by taking the id of the field that already says what field it is. If the value of the field is correct according to the criteria that you establish, you add it to the array that will be used later and return 'true'.

That is, 'every ()' returns true if all values meet a condition that you set or false if any of them does not set that condition.

'trim ()' removes the first and last spaces of a tring, if you put only spaces this would remove them.

So, as soon as the 'every' method returns a false by the condition you want, valid is false.

    const values = [];
    let valido = [].every.call(inputs, input => {
        if (input.value.trim() === "") {
            alert("Inserta el campo "+input.id+". Si no lo ha hecho, ingreselo.");
            return false;
        }
        else {
            values.push(input.value);
            return true;
        }
    });



    if(valido) {
        const tds = row.querySelectorAll('td');
        [].forEach.call(tds, (td, i) => {
          if (i === 0) { td.textContent = i + 1; }
          else { td.innerHTML = values[i - 1]; }
        });
        reordenar();
    }
    
answered by 20.07.2017 в 23:55