I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
To make checkbox behave like radio buttons with JavaScript, we can listen to the body element's click listener. And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that's clicked. to add the checkboxes.
Answers 1 : of How to make a checkbox behave like a radio button in react. You can use ref with checkboxes, and onClick for each of them, by using ref you can unCheck the box.
Checkboxes allow the user to choose items from a fixed number of alternatives, while radio buttons allow the user to choose exactly one item from a list of several predefined alternatives.
If a radio button is checked, its checked property is true . Then, we assign the value of the selected radio button to the selectedSize variable. Since only one radio button in a radio group can be checked at a time, the loop is terminated immediately by the break statement.
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label> <label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label> <label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label> <label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() { $(".chb").prop('checked', false); $(this).prop('checked', true); });
if you want user can unchecked selected item :
$(".chb").change(function() { $(".chb").not(this).prop('checked', false); });
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){ e = e || event; var cb = e.srcElement || e.target; if (cb.type !== 'checkbox') {return true;} var cbxs = document.getElementById('radiocb') .getElementsByTagName('input'), i = cbxs.length; while(i--) { if (cbxs[i].type && cbxs[i].type == 'checkbox' && cbxs[i].id !== cb.id) { cbxs[i].checked = false; } } }
Here's a working example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With