Home » Jquery » javascript – How to pick color from buttons

javascript – How to pick color from buttons

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have html tables,and I would like to change its colors by picking up from button and clicking cells.

First,I would like to select colors from buttons,

Second,When I select colors from buttons,I would like to click cells to change color.

Third,After selecting colors,Can I change cell’s color by clicking on it?

<tr>
<td>color</td>
</tr>

<button>yellow</button>
<button>aqua</button>

At first I assume it will realize by changing td’s class,but I couldn’t find out the ways.

If someone has experienced such method,please let me know.

Thanks

td {
  background-color: yellow;
  }

td {
  background-color: aqua;
  }
How to&Answer:

Try this once. It’s working

var color = 'black';

$('.click_btn').on('click', function(e) {
  e.preventDefault();
  color = $(this).css('color');
})

$('.click_td').on('click', function(e) {
  e.preventDefault();
  $(this).css('color', color);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="click_td">color</td>
    <td class="click_td">color II</td>
  </tr>
</table>
<button class="click_btn" style="color:yellow;">yellow</button>
<button class="click_btn" style="color:aqua;">aqua</button>

Answer:

Use this code-

$(document).ready(function(){
  $("#color1").click(function(){
    $(".table td").css("background","red");
  });
  $("#color2").click(function(){
    $(".table td").css("background","aqua");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>My First Web Page</title>
</head>
<body>
<h1>My Table</h1>
<table class="table">
    <tr>
        <th>Airport Code</th>
        <th>Common Name/City</th>
    </tr>
    <tr>
        <td>CWA</td>
        <td>Central Wisconsin Airport</td>
    </tr>
    <tr>
        <td>ORD</td>
        <td>Chicago O'Hare</td>
    </tr>
    <tr>
        <td>LHR</td>
        <td>London Heathrow</td>
    </tr>
</table>

<button id="color1">Select Red</button>
<button id="color2">Select aqua</button>

</body>
</html>