Making checkboxes behave like radio buttons

Started by abcdf, 10-24-2011, 20:58:15

Previous topic - Next topic

abcdfTopic starter

Hi

For reasons that would take too long to explain, I need to make a group of three select boxes behave like radio buttons ie if you click one of the three, any previously selected one is deselected.

Anyone know of a javascript that would do this?

many thanks


dhamaka

Yes, there is a JavaScript solution that can make a group of three select boxes behave like radio buttons. Here's an example code snippet:

```javascript
// Get references to the three select boxes
var selectBoxes = document.querySelectorAll('.select-box');

// Add event listeners to each select box
for (var i = 0; i < selectBoxes.length; i++) {
  selectBoxes.addEventListener('change', function() {
    // Deselect all select boxes
    for (var j = 0; j < selectBoxes.length; j++) {
      selectBoxes[j].selectedIndex = 0;
    }
    // Select the clicked select box
    this.selectedIndex = 1;
  });
}
```

In this code, you first need to assign a common class name (e.g., 'select-box') to each select box you want to include in the group. Then, the JavaScript code will add an event listener to each select box, so when a select box is changed, it will deselect all the other select boxes and select the one that was clicked.

Make sure to replace '.select-box' with the actual class name you use for your select boxes.
  •