domingo, 27 de octubre de 2013

Dealing with generated code in HTML

Last night one friend of my calls me to help him with the application they use at the school he works. He wanted to have the final grades less than 70 with red color. It's only a one java-script function he tells me. And it's true. But there is a hidden story in that simple java-script function.

First of all. I start checking that the table is a generated table. No problem with this. But then i noticed something funny all the rows have the same ID. WTF was my first impression.
 <TD class=xl30 id="table1">{rc_ClassAvg1} </TD>  
 <TD class=xl30>>&nbsp;</TD>  
 <TD class=xl30 id="table2">>{rc_ClassAvg2} </TD>  
 <TD class=xl30>&nbsp;</TD>  
 <TD class=xl30 id="table3">{rc_ClassAvg3} </TD>  
rc_ClassAvg1 generates the code for all the grades, and all the rows it generates come with id=table1.

So my simple java-script file had to deal with repeated rows with the same idea. Looking at stackoverflow I found this question.

It help me deal with the generated code that had the same id.


 this.changecolor = function(){  
  var value;  
  var id;  
   var n = document.getElementById("table1");  
   var a = [];  
   var y=1;  
   while(n) {  
     a.push(n);  
     n.id = "table"+y;  
   y=y+1;  
     n = document.getElementById("table");  
  }  
  for(i=0;i<a.length;i++){  
   elementid=a[i].id;  
   value=document.getElementById(elementid).innerHTML;  
   if (value < 70 ){  
    document.getElementById(elementid).style.color='red';  
   }  
  }  
 };  
At the end I have to go by each element change the element id and put this elements in an array.
This would have been solved other way if my generated code didn't include the same id for each element. I guess that's a bug.

Just wondering what solution would have you done?

6 comentarios:

  1. The line inside the while loop:

    n = document.getElementById("table");

    Shouldn't be?
    n = document.getElementById("table1");

    ResponderEliminar
    Respuestas
    1. Yeah! That's typing issue. I am going to updated.

      Eliminar
  2. Another problem would be that the "Table2" and "Table3" elements already exist and it will get duplicated, maybe you want to usen another id like "Table_n".

    ResponderEliminar
  3. Wouldn't it be better to use HTML5 form validation for things like this? If it's possible, then it should be a lot easier, a lot faster to code and a much more efficient.

    ResponderEliminar
    Respuestas
    1. I mean something like this in html:

      «input required type="number" min="70" max=100" value="55"»

      And then a style sheet such as this:

      «style»
      input:invalid { background-color:red; }
      «/style»

      Eliminar
    2. Yes! You are right. But there is a big issue. The place where they will use this they use IE8. HTML5 will not work

      Eliminar