I am new to Javascript and I am making a program where you can add rows to a table, write your data and insert them into the table itself, what I want it to do is that when you enter a row another row is not entered:
For example:
I click the "add a row" button, but I have not added any data to it and when I click again on the "add a row" button, it prevents me from doing so and I get an alert that tells me that a row will not be added If I don't fill in the required fields (Name, Area, Position and Email)...
This is my JavaScript code:
$(document).ready(function() {
$('#bt_add').click(function() {
agregar();
});
$('#bt_del').click(function() {
eliminar(id_fila_selected);
});
$('#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> </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();
}
/*
* Esta función agrega lo ingresado a la tabla
*/
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]; }
});
}
}
function seleccionar(id_fila) {
if ($('#' + id_fila).hasClass('seleccionada')) {
$('#' + id_fila).removeClass('seleccionada');
} else {
$('#' + id_fila).addClass('seleccionada');
}
//2702id_fila_selected=id_fila;
id_fila_selected.push(id_fila);
}
function eliminar(id_fila) {
/*$('#'+id_fila).remove();
reordenar();*/
for (var i = 0; i < id_fila.length; i++) {
$('#' + id_fila[i]).remove();
}
reordenar();
}
function reordenar() {
var num = 1;
$('#tabla tbody tr').each(function() {
$(this).find('td').eq(0).text(num);
num++;
});
}
function eliminarTodasFilas() {
$('#tabla tbody tr').each(function() {
$(this).remove();
});
}
You can add a review when you click
bt_add
You use an array to see enter the IDs of the fields that are not filled and at the end you ask if the array is empty, if it is empty it means that all the data is full. The problem with this is that it will check all the rows, I've already entrusted you with the way you can check only the last row, that's your turn.
Look for the input in the last TR and check that value is not empty
In your code you will have the input IDs repeated for each row, be careful with that
Add unique id's for each input and review only those id's.