user2371301
user2371301

Reputation: 3474

Putting dynamically created ID into javascript

So I have a script that auto-generates ID's based on a column in a database. like such:

echo "<tr class='task' id='task-" . $row['task_id'] . "'>";

And then I have a script that is below that I am wanting it to change each tr class name based on some information from another column. I tried placing the same code 'task-". $row[task_id] ."' into the document.getElementById field but it didn't resolve in the browser. resolve meaning it stayed as 'task-" . $row[task_id] . "' instead of changing $row[task_id] into a number. I need to make that change to a number so it matches the id's of the tr.

var resolved = <?php echo $_SESSION['resolved']; ?>;
    if (resolved == 1) 
    {
        document.getElementById('task-" . $row[task_id] . "').className ="task resolved";
    }
    else
    {
        document.getElementById('task-" . $row[task_id] . "').className =" task";
    }

Upvotes: 1

Views: 50

Answers (2)

Kylie
Kylie

Reputation: 11749

No need for javascript, if your status is in a column of that table....

if($row['resolved']=="1){
    $class="task resolved";
} else {$class = "task";}

echo "<tr class='".$class."' id='task-" . $row['task_id'] . "'>";

Or a much simpler version...

echo "<tr class='task ".($row['resolved'] == 1 ? 'resolved' : '')."' id='task-".$row['task_id']."'>";

Upvotes: 0

chrislondon
chrislondon

Reputation: 12031

You need to echo out the variables like so:

var resolved = <?php echo $_SESSION['resolved']; ?>;

if (resolved == 1) 
{
    document.getElementById('task-<?php echo $row['task_id'] ?>').className ="task resolved";
}
else
{
    document.getElementById('task-<?php echo $row['task_id'] ?>').className =" task";
}

But it's better to not do it in javascript but to just do it in your PHP like so:

echo "<tr class='task " . ($_SESSION['resolved'] == 1 ? 'resolved' : '') ."' id='task-" . $row['task_id'] . "'>";

that adds the resolved class to as you are generating your HTML. However you will probably need a better way to test if a task is resolved because with the $_SESSION['resolved'] == 1 it's going to mark ALL tasks as resolved. So assuming your row has a column like `$row['resolved'] you could do:

echo "<tr class='task " . ($row['resolved'] == 1 ? 'resolved' : '') . "' id='task-$row[task_id]'>";

Upvotes: 2

Related Questions