Ali ATriple
Ali ATriple

Reputation: 179

Javascript is not positioned correctly

I'm having problems with my javascript. I have to colocate an image in a specific position. The user gives me a date and I put an image for the correct month of the year. For example if they put 01/05/1936, an image appears on a table in the row "1936" on the colummn "5" , so I have 2, each one for the years an another for the months. The month is correct but it puts the image in all rows, and I don't know why, here is my code:

On the HTML part I only have a table with id="tabla" and 2 rows one with id="1935" and the other with id="1936", each td has the class of the correct month:

   <tr id="1935">
    <th>1935</th>

<td class="E"></td>
<td class="F"></td>
<td class="M"></td>
<td class="A"></td>
<td class="Y"></td>
<td class="J"></td>
<td class="L"></td>
<td class="G"></td>
<td class="S"></td>
<td class="O"></td>
<td class="N"></td>
<td class="D"></td>

</tr>
<tr id="1936">
    <th >1936</th>

<td class="E"></td>
<td class="F"></td>
<td class="M"></td>
<td class="A"></td>
<td class="Y"></td>
<td class="J"></td>
<td class="L"></td>
<td class="G"></td>
<td class="S"></td>
<td class="O"></td>
<td class="N"></td>
<td class="D"></td>

</tr>

` Javascript code

var filas=document.getElementById("tabla").rows.length;//I count the rows, years
    var cols = $("#tabla").find('tr')[0].cells.length;//I count the td, months


       $("tr").each(function(a){
        var fila= $(this);

        alert("Primer alert"+fila.attr("id"));
        if (fila.attr("id")==anio)
        {
           $("td").each(function(a)
            { 
            var col=$(this);

            alert("segundo alert"+col.attr("class"));
                if (col.attr("class")==mon)
                {
                    $(this).prepend('<img id="black_point" src="./images/circle.png"/>');
                }
           });
        }
        });`

Upvotes: 4

Views: 65

Answers (2)

Samurai
Samurai

Reputation: 3729

You're going through all tds not only the ones inside that tr, so you need to change:

$("td").each(function(a)

to

fila.find($('td')).each(function(a)

Upvotes: 2

Roamer-1888
Roamer-1888

Reputation: 19288

With jQuery, looping can very often be avoided.

As far as I can tell, you can select the correct table cell with a single jQuery selector ...

function foo(anio, mon) {
    $('#' + anio + ' .' + mon).prepend('<img id="black_point" src="./images/circle.png"/>');
}

Please note that I have assumed a function wrapper not shown in the question.

Upvotes: 3

Related Questions