Vishal B
Vishal B

Reputation: 653

how to change style of button on click and click on different button it should be change to default

I have numbers of buttons, i want to change style of button on click event, but after click on another button that button style should be change to default... i am fetching buttons from DB like

<table  class="table">
  <thead>
   <tr>
      <th style="text-align: center;">Tables</th>
   </tr>
  </thead>
  <tbody>
    @foreach($tables as $table)
    <tr id="table">
      <td style="text-align: center;">
        <button class="btn" >{{$table->table_no}} </button>
      </td>
     </tr>
     @endforeach
   </tbody>
 </table>

my script is:

$('#table button').click(function(){
    $(this).css('background-color','green');
  });

problem is if i click different button background color of that button should be change to default, how can I get this?? plz help, than you.

Upvotes: 2

Views: 635

Answers (3)

Daniel
Daniel

Reputation: 135

You can do this only by CSS, add below into your style:

button { 
   background: grey;
}
button:active { 
   background: green;
}

Upvotes: 0

mplungjan
mplungjan

Reputation: 177691

IDs need to be unique so I removed the IDs from the rows.

I also moved the inline CSS to a stylesheet.

Your loop content should look like this now

<tr>
  <td>
    <button class="btn" >{{$table->table_no}} </button>
  </td>
 </tr>

Example code

$(function() {
  $('#table button').on("click",function(e){
    e.preventDefault();
    $('#table button').removeClass("selected");
    $(this).addClass("selected");
  });
});  
#table th,td { text-align: center; }
.selected { background-color:green }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table" class="table">
  <thead>
   <tr>
      <th>Tables</th>
   </tr>
  </thead>
  <tbody>
    <tr>
      <td>
        <button class="btn" >{{$table->table_no}} </button>
      </td>
     </tr>
    <tr>
      <td>
        <button class="btn" >{{$table->table_no}} </button>
      </td>
     </tr>
    <tr>
      <td>
        <button class="btn" >{{$table->table_no}} </button>
      </td>
     </tr>
    <tr>
      <td>
        <button class="btn" >{{$table->table_no}} </button>
      </td>
     </tr>

   </tbody>
 </table>

Upvotes: 4

Related Questions