Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

changing all <td> color onclick for a particular table

iam using below code to toggle td color

    <html>
    <head>
       <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
       <script>
          $(function(){
             $("td").click(function(){
             $(this).addClass("on").parent().siblings("tr").find("td").removeClass("on");
             });
          });
       </script>
       <style>
          article, aside, figure, footer, header, hgroup, 
          menu, nav, section { display: block; }
          .on { background-color:red; color:#ffffff; }
       </style>
    </head>
    <body>

    <table class="mytable" border=1>
       <tbody>
       <tr>
          <td>Hello World</td>
          <td>Hello World1</td>
          <td>Hello World2</td>
       </tr>
       <tr>
          <td>Hello World</td>
          <td>Hello World1</td>
          <td>Hello World2</td>
       </tr>
       <tr>
          <td>Hello World</td>
          <td>Hello World1</td>
          <td>Hello World2</td>
       </tr>
       </tbody>
    </table>

    </body>
    </html>

above code works fine by toggling td color, please check the demo here

but now i need to do three things,

  1. above code is working for all the tds ,i need it to work only for last column of table class "mytable",
  2. i need to add a button which when clicked should change all td's color to "white" of table class "mytable"
  3. compleate row should be red color when we select partcular cell. please help me to fix this
like image 456
Friend Avatar asked Sep 10 '12 08:09

Friend


1 Answers

HTML

  <table class="mytable" border=1>
    <tbody>
      <tr>
        <td>Hello World</td>
        <td>Hello World1</td>
        <td>Hello World2</td>
      </tr>
      <tr>
        <td>Hello World</td>
        <td>Hello World1</td>
        <td>Hello World2</td>
      </tr>
      <tr>
        <td>Hello World</td>
        <td>Hello World1</td>
        <td>Hello World2</td>
      </tr>
    </tbody>
  </table>

<button id="change-color">Change Color</button>

jQuery

$(function() {
    $(".mytable tr td:last-child").click(function() {
        $(this).addClass("on").parent().siblings("tr").find("td.on").removeClass("on");
    })

    $('#change-color').click(function() {
        $('.mytable td.on').removeClass('on');
    });
});​

DEMO

According to comment

$(function() {
    $(".mytable tr td:last-child").click(function() {
        $('td.on').removeClass('on');
        $(this).parent().find('td').addClass("on");
    })

    $('#change-color').click(function() {
        $('.mytable td.on').removeClass('on');
    });
});​

Demo

like image 111
thecodeparadox Avatar answered Sep 19 '22 01:09

thecodeparadox