Javascript base javascript loop nr iterations in php loop ierations

Consider the following code, which takes time from the database, javascript gets the selectbox value and does the countdown calculation.

var seconds = document.getElementById("countTime").textContent;
var seconds = seconds*3600;
function timer() {
 //somecode
}

echo'<td id="countTime" style="">';
                    echo    $days_remaining.$hours_remaining;
                        echo'</td>';

      

It works like a charm and I am getting this output

enter image description here

But here are my problems:

  • I am generating invalid html in echo'<td id="countdown"

    ... ok I can easily fix this by declaring an array and adding it to id:<td id="countdown'.$nr." //assume $nr = 1 ++

    BUT

  • My big problem is my jscript code, the above javascript only works for the 1st td element, the element <td>

    is in the loop and the nr elements <td>

    are based on the number of loop iterations

THIS

  • How do I change the jscript above to return the countdown time inside each element <td>

    ? Can i do itvar seconds = document.getElementById( var seconds = document.getElementById("countTime".nr++).value;).innerText;

  • Obviously I would have to use a loop, but how would I get the number of javascript loops to iterate over based on php while loop nr iterations? I suppose I can count the number of php loop iterations by $var++

    displaying it in an element and getting the .innerText value, however that seems terribly inefficient.

I may have overdone it, but I'm stuck ...

+3


source to share


1 answer


As mentioned in the comments, use a generic class on <td>

s. Then change your Javascript to use querySelectorAll

:



var elements = document.querySelectorAll('.countTime');
var seconds, i;

// elements now contains an object, that contains all elements
// that have the class 'countTime'

for (i = 0; i < elements.length; i++) {
    seconds = elements[i].textContent * 3600;
    // etc...
}

      

+1


source







All Articles