Button Group With Selected Button

Hi. Is there a way to create a button group in HTML in which one button is selected?

Say unselected buttons are green and the selected button is blue. I would want the user to select a button by clicking on it, causing the color of the button to turn blue and the color of the previously selected button to turn green. Some other visual indication of the change would also be good.

I would also want it to call a function (like onClick when clicking one button). Finally, I would want there to be a variable with a value associated with the selected button (e.g. 1 for the first button, 2 for the second and so on) which can be used (for example, as input when calling the function).

Is the best way to do this to code this in JavaScript? Is there a library like Bootstrap which would have what I’m looking for?

if you use java script, you can do this.
first of all, you should set the class name of group div to btn-group.
then, set all buttons class name to ‘unselected’ except for one, to selected.
in javascript part. you should remove the class name unselected if it clicked, then add class name selected. after that, another buttons class name should initialized to unselected.
below code will help you. it’s similar to your problem, not just same.
hope it will help you.

1 Like

Thank you so much! The code you included was very useful.