Jquery Change CSS of variable div

130 views Asked by At

I have a table with a bunch of td with the classes markTD and they each have a different integer for the attribute value. I would like to click the button called mark and change the color of just 1 of the td.

 $('#mark').click(function(){
    var h2 = parseInt($('#h2').attr('value'), 10);
    //h2 returns the number 3
        $('#markTD').find('value',h2).css("color","red");  //this is the line that's not working

}

HTML

<table id='markTable'>
<tr>
    <td>Question number:</td>
    <?php 
        $q=1;
        while ($q <= $num_rows){
            echo "<td class='markTD' value='" . $q . "'>" . $q .  "</td>";
            $q++;
        }

    ?>
</tr>
</table>
3

There are 3 answers

1
Ziregbe Otee On BEST ANSWER
See the answer in javascript:

1. In your function get all the tds in collection.

2. Get the length of the collection.

3. Get a random value from 0 to the (length - 1) of your collection.

4. Use the random number to access one of your tds and change the colour.

See sample html below:


<html>
<head>
<script>

function ChangeColor()
{

    var tdCol = document.getElementsByClassName("markTD");

    var length = tdCol.length;

    var randomTdIndex =  Math.floor(Math.random() * (length - 0)) + 0 ;

 /* clear all colors // this loop is not important. I used it to clear all colors just incase there was a coloured td */

   for(var i = 0 ; i < length ; i++)
   {
    tdCol[i].style.backgroundColor = "white";
   }

    tdCol[randomTdIndex].style.backgroundColor = "red";

} 

</script>
</head>

<body>
<table>
<tr><td class="markTD" >td 1</td><td class="markTD">td 2</td></tr>
<tr><td class="markTD">td 2</td><td class="markTD">td 4</td></tr>
<tr><td class="markTD">td 5</td><td class="markTD">td 6</td></tr>
</table>

<input type="button" onclick="ChangeColor()" value="Update TD" />
</body>
</html>
0
KidBilly On
 $('#markTD').find('value',h2).css("color","red");

This line isn't working because find only takes one argument, the selector

Try using a $('#markTD').each, then use .css() to return and check the values you need.

0
Fil0z0 On

You can use the .eq() method fot choose witch td you want to change, for example with the 0 value you take the first element jQuery array

  $('#markTD').find('value',h2).eq(0).css("color","red");