Dhaval Gosai
Dhaval Gosai

Reputation: 21

Change color of text in row by checkbox in same row in table

I am creating a very simple table having two columns 1.Text 2.Checkbox. i want that whenever i make the checkbox checked corresponding row's text color should be changed. i don't know how to do that.can anyone guide please?

i tried this way but didn't work. here's the code:

<?php

    $var=1;
    $cbid = "chechbox".$var;

     echo"<table>
            <tr>
               <th>Text</th>
               <th>Checkbox</th>
            </tr>";

    while($var<=3){
        echo"
              <tr>
                 <td>
                     <input type='text' id='$var' value='$var'>
                 </td>
                 <td>
                    <input type='checkbox' id='$cbid' onclick='fun()'> 
                 </td>
              </tr>   
           </table>

        <script>
            function fun(){
                var a = document.getElementById($var);
                var b = document.getElemeentById($cbid);
                if(b.checked == true){
                     a.style.color='red';
                }
            }      
        </script>
        ";

        $var++;
        $cbid = 'chechbox'.$var;
    }
?>
     

i am beginner. i am not even sure if i can make multiple script using while loop.

Upvotes: 1

Views: 490

Answers (1)

VebDav
VebDav

Reputation: 162

You can do so:

document.getElementById('check').onchange = function () {
    let textVar = document.getElementById('tableText');
    if (document.getElementById('check').checked) {
        textVar.style.color = 'red';
    } else {
        textVar.style.color = 'green';
    }
}
<table>
  <tr>
    <th>Text</th>
    <th>Checkbox</th>
  </tr>
  <tr>
    <td><input type='checkbox' id='check' value='$var'></td>
    <td><input type='text' id='tableText' value='$var'></td>
  </tr>  
</table>

Upvotes: 1

Related Questions