K Ahir K Ahir - 2 months ago 8
CSS Question

HTML - How to change button background color on OnClick event

I have following PHP code where 4 buttons are displaying dynamically from database table. Different content is displaying on page based on clicked button.

Now, I want to do so when I click 1st button then button bg color should be changed so visitor can know which button is pressed. When 2nd button is clicked then bg color of that button should be changed and previously clicked button (1st button in this example) should be restored with original color.

Please let me know easiest way to do this using either CSS or Javascript.

<form name="frm_list" action="toptipper.php" method="post" enctype="multipart/form-data">

<?php
while(!$rs_tab_list->eof())
{
?>

<button type="submit" name="btn_tab" value="<?php print($rs_tab_list->fields("tabpkid")); ?>"><?php print($rs_tab_list->fields("title")); ?></button>

<?php
$rs_tab_list->movenext();
}
?>

</form>

Answer

Uncomment out the comment marks if you want only one selected at a time.

$('button').on("click",function(){  
  //$('button').not(this).removeClass();
  $(this).toggleClass('active');
  
  });
.active{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>

Comments