Change “tr” color of a table depending on timer with JavaScript or jQuery

Change “tr” color of a table depending on timer with JavaScript or jQuery
0

#1

Hi I’m stuck in the following problem I created a form with html, bootstrap, js, and jQuery, it works I can add and delete rows normally. But I need to put a timer in every row of 2 hours, I did a simple one but I cant put it on the row “time left” I want to add multiple rows and if the timer reaches 0 the “tr” should turn color red. Any help will be great!

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html lang= "es">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<title>
TABLE
</title>


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<h2 align=center>TABLE</h2> 






    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>


<style type="text/css">
form{
    margin: 20px 0;
}
form input, button{
    padding: 5px;
}
table{
    width: 100%;
    margin-bottom: 20px;
	border-collapse: collapse;
}
table, th, td{
    border: 1px solid #cdcdcd;
}
table th, table td{
    padding: 10px;
    text-align: left;
}

</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
      $(".add-row").click(function(){
          var id = $("#txtID").val();
          var job= $("#txtJob").val();
  		var heat= $("#txtHeat").val();
		var probeta= $("#txtProbeta").val();
		var line= $("#txtLine").val();
           var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + id + "</td><td>" + job + "</td><td>" 
+ heat + "</td><td>" + probeta + "</td><td>" + line + "</td><td>" + line + "</td><td><input type='button' class='btn 
btn-primary'name='phaseA'value='Phase A'></td><td><input type='button'class='btn btn-warning' 
name='phaseB'value='Phase B'></td><td><input type='button' class='btn btn-success' name='phaseC'value='Phase C'></td><td><input type='button' class='btn btn-danger'name='phaseD'value='Phase D'></td><td>" + line + "</td><td>" + line + "</td></tr>";
          $("table tbody").append(markup);
      });																																																																
    
        // Find and remove selected table rows
         $(".delete-row").click(function(){
          $("table tbody").find('input[name="record"]').each(function(){
        	  if($(this).is(":checked")){
                  $(this).parents("tr").remove();
              }
           });
       });
    });    
</script>
</head>
<body>
<div class="container">
   <form id="frmPerson">


     
	 
	 <input type="text" id="txtID" class="form-control" placeholder="LOG" onKeyUp="autofill(event)" >
    <input type="text" id="txtJob" class="form-control" placeholder="JOB" >
	<input type="text" id="txtHeat" class="form-control" placeholder="HEAT" >
	 <input type="text" id="txtProbeta" class="form-control" placeholder="SAMPLE" >
	 <input type="text" id="txtLine" class="form-control" placeholder="LINE" >
	<input type="button" class="add-row btn-primary" value="Add Row">
	<div id="hms">00:00:10</div>
</form>
<table id="tblList" class="table-responsive">
    <thead>
        <tr>
		 <th>INDEX</th>
            <th>LOG</th>
            <th>JOB</th>
            <th>HEAT</th>
			<th>SAMPLE</th>
			<th>LINE</th>
			<th>STARTED AT</th>
			<th>PHASE A</th>
			<th>PHASE B</th>
			<th>PHASE C</th>
			<th>PHASE D</th>
			<th>FINISHED AT</th>
			<th>TIME LEFT</th>
			
        </tr>
    </thead>
    <tbody>
   
    </tbody>
</table>
<button type="button" class="delete-row btn-danger">Delete Row</button>
<script>
	$('#frmPerson').on('keyup keypress', function(e) {
  var keyCode = e.keyCode || e.which;
  if (keyCode === 13) { 																		<!--
ESTE SCRIPT EVITA QUE SE ENVIE EL FORMULARIO POR DEFECTO AL PRESIONAR ENTER-->
   e.preventDefault();
   return false;
      }
  });
   </script>

<script src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
 function autofill(e){
	 var e=e || window.event;
   var keycode=e.which || e.keyCode;
   if(keycode !== 13 || (e.target||e.srcElement).value=='') 
return false;
	 var txtID = $("#txtID").val();
	 $.ajax({
		 url:'autofill-ajax2.php',
		 data:'txtID='+txtID,
	 }).success(function(data){
			var json = data,
			obj = JSON.parse(json);
			$("#txtJob").val(obj.jobphp);
			$("#txtHeat").val(obj.heatphp);
			$("#txtProbeta").val(obj.probetaphp);
			$("#txtLine").val(obj.linephp);
	 });
 }
</script>
<script>
    var tiempoTrabajo;
	var counter = 10;

    function CambiarColorColumna(message){
	var tabla = document.getElementById("tblList").getElementsByTagName("tr");
	tabla[3].style.backgroundColor="red";
	
  }
  function count(){
    var startTime = document.getElementById('hms').innerHTML;
    var pieces = startTime.split(":");
    //console.log(pieces);
    var time = new Date();    
    time.setHours(pieces[0]);
    time.setMinutes(pieces[1]);
    time.setSeconds(pieces[2]);
    var timedif = new Date(time.valueOf() - 1000);
    var newtime = timedif.toTimeString().split(" ")[0];
    document.getElementById('hms').innerHTML=newtime;
    counter--;
    if(!counter){
    	clearTimeout(tiempoTrabajo);
        CambiarColorColumna();
        return;
      }
      }
      function countdown(){
    	tiempoTrabajo=setInterval(count, 1000);
       }
   countdown()
  function detenerTimer() {
  clearTimeout(tiempoTrabajo);
}
   </script>

 </body> 
</div>
</html>          
**JAVACRIPT**    
           $(function () {
      var operation = "C"; //"C"=Crear
    var selected_index = -1; // Indice de el elemento seleccionado en la lista
  var tblPersons = localStorage.getItem("tblPersons"); //Retornar los datos almacenados
  tblPersons = JSON.parse(tblPersons); //Convertir String a Object
  if (tblPersons === null) // Si no hay datos, inicializar un array vacio
     tblPersons = [];

  function Create() {
   //Obtener los valores de la forma HTML y transformalos en String.
   var person = JSON.stringify({
     ID: $("#txtID").val(),
    Job: $("#txtJob").val(),
    Heat: $("#txtHeat").val(),
  Probeta: $("#txtProbeta").val(),
  Line: $("#txtLine").val(),
  Tiempo:$("#mhs").val("00:00:10")
    }); 
   //Añadir el objeto a la tabla
   tblPersons.push(person);
   //Almacenar los datos en el Local Storage
   localStorage.setItem("tblPersons", JSON.stringify(tblPersons));
   alert("Los datos han sido almacenados"); //Mensaje de alerta
   return true;
   }

   function Edit() {
   // Editar el item seleccionado en la tabla
    tblPersons[selected_index] = JSON.stringify({
    ID: $("#txtID").val(),
   Job: $("#txtJob").val(),
   Heat: $("#txtHeat").val(),
  Probeta: $("#txtProbeta").val(),
  Line: $("#txtLine").val(),
    Tiempo:$("#mhs").val("00:00:10")
     });
      //Almacenar los datos en el Local Storage
    localStorage.setItem("tblPersons", JSON.stringify(tblPersons)); 
    alert("Los datos han sido editados"); //Mensaje de alerta
    return true;
  }

   function Delete() {
    //Eliminar el elemento seleccionado en la tabla
    tblPersons.splice(selected_index, 1); 
    //Actualizar los datos del Local Storage
   localStorage.setItem("tblPersons", JSON.stringify(tblPersons)); 
    alert("Persona Eliminada"); //Mensaje de alerta
  }

  function List() {
    $("#tblList").html("");
   $("#tblList").html(
        "<thead>" +
        "<tr>" +                
        "<th>LOG</th>" +
        "<th>JOB</th>" +
        "<th>HEAT</th>" +
        "<th>SAMPLE</th>" +
		"<th>LINE</th>" +
		"<th>TIMER</th>" +
        "<th>OPTIONS</th>" +
        "</tr>" +
        "</thead>" +
        "<tbody>" +
        "</tbody>"
        ); //Agregar la tabla a la estructura HTML
    for (var i in tblPersons) {
    var per = JSON.parse(tblPersons[i]);
    $("#tblList tbody").append("<tr>" +                    
            "<td>" + per.ID + "</td>" +
            "<td>" + per.Job + "</td>" +
            "<td>" + per.Heat + "</td>" +
            "<td>" + per.Probeta + "</td>" + 
			"<td>" + per.Line + "</td>" + 
			"<td>" + per.Tiempo + "</td>" + 
            "<td><img src='edit.png' alt='Edit" + i + "' class='btnEdit'/>&nbsp &nbsp<img src='delete.png' alt='Delete" + i + 
 "' class='btnDelete'/></td>" +
            "</tr>"
            );
     } //Recorrer y agregar los items a la tabla HTML
  }

   $("#frmPerson").bind("submit", function () {
    if (operation === "C")
    return Create();
    else
    return Edit();
   }); //Función para decidir si se encuentra añadiendo o editando un item

    List();

  $(".btnEdit").bind("click", function () {
    operation = "E"; //"E" = Editar
   //Obtener el identificador del item a ser editado
   selected_index = parseInt($(this).attr("alt").replace("Edit", ""));
   // Convertir de JSON al formato adecuando para editarlos datos
    var per = JSON.parse(tblPersons[selected_index]); 
   $("#txtID").val(per.ID);
    $("#txtJob").val(per.Job);
   $("#txtHeat").val(per.Heat);
    $("#txtProbeta").val(per.Probeta);
 $("#txtLine").val(per.Line);
  $("#mhs").val(per.Tiempo);
   $("#txtID").attr("readonly", "readonly");
   $("#txtName").focus();
  });

  $(".btnDelete").bind("click", function () {
   //Obtener el identificador del item a ser eliminado
   selected_index = parseInt($(this).attr("alt").replace("Delete", "")); 
    Delete(); //Eliminar el item
    List(); //Volver a listar los items en la tabla
 });
});

#2

fiddle https://jsfiddle.net/30yxe3f7/


#3

I am having trouble visualizing what you want to happen. Can you try to explain with more details what you want to happen. Currently, the page loads and a counter counts down to 0:00:00. There is an Add Row button which inserts rows in a table with no data in them. Are you wanting something different to happen with the click of Add New or something completely different all together?


#4

Hi first of all this my new attemp https://jsfiddle.net/kuen837h/
The counter should be inside a table row when is inserted as you can see in this new example the counter is at the end of every row but only the first one works.
If the counter reaches 0 the row should turn to color red and when you press any of the buttons they should disable one by one. if you still have questions plz let me know Im really stuck T_T


#5

I reorganized your code in a new fiddle.net because it was very difficult to follow. Basically, I moved the type of content (html, css, JavaScript) to each applicable section in the fiddle.

Next in the JavaScript section, your code was not organized at all, so I moved all the functions to the top and the main code to the bottom. I added a new variable called rowID which starts at one and is incremented inside the Add New button click event. rowID is used in that function to create a unique id attribute for each row added (see fiddle). Later when the timer gets to 0:00, then it is assumed the most recent rowID - 1 is the row which needs the background changed to the color red.

https://jsfiddle.net/63qbgjjo/2/

As you will see, the main part of the code is really just:

    var rowID = 1; // global variable used for unique ID for each row
    var tiempoTrabajo; 
    var counter = 10;
    countdown(); 
    var operation = "C"; //"C"=Crear
    var selected_index = -1; // Indice de el elemento seleccionado en la lista
    var tblPersons = localStorage.getItem("tblPersons"); //Retornar los datos almacenados
    tblPersons = JSON.parse(tblPersons); //Convertir String a Object
    if (tblPersons === null) // Si no hay datos, inicializar un array vacio
        tblPersons = [];
    List();

To have more than one timer, you are going to have to use a data structure such as an array or object to store each timer. I will let you figure that part on your own.

NOTE:
We are primarily here to help people with their Free Code Camp progress, but sometimes like I have done for you, we try to help where we can. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at http://freecodecamp.com.

Happy coding :slight_smile:


#6

thanks for the help :slight_smile: