19

Is there a way to make checkboxes act like radio buttons? I assume this could be done with jQuery?

<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />

<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />

If one box was checked the others in the group would uncheck.

jzd
  • 23,473
  • 9
  • 54
  • 76
superUntitled
  • 22,351
  • 30
  • 83
  • 110
  • 19
    Why not use actual radio buttons? Using checkboxes as radio buttons is going to confuse the hell out of your users. – BoltClock Jan 15 '11 at 04:10
  • 9
    I could dress my dog like a cat, but wouldn't it be smarter to just get a cat? – jondavidjohn Jan 15 '11 at 04:11
  • @Phrogz: Was I not serious enough? :/ – BoltClock Jan 15 '11 at 04:14
  • thanks for the fair warnings! i know this is a terrible idea. I have no excuse. – superUntitled Jan 15 '11 at 04:27
  • 2
    @BoltClock One cannot uncheck a radio button unlike a checkbox. – ᴍᴀᴛᴛ ʙᴀᴋᴇʀ Dec 06 '16 at 11:25
  • years pass and I have one big explanation why this concept is cool! I dont know why but all radio buttons and toggle stuff from bootstrap (when I creating them dynamicly from code by js) doesn't work for me ... (for example, group of radio button dosent unchecked when the other was clicked), but checkboxes works always with answers from this topic works always. – szkut Jul 17 '19 at 03:55

11 Answers11

45
$("input:checkbox").click(function(){
    var group = "input:checkbox[name='"+$(this).attr("name")+"']";
    $(group).attr("checked",false);
    $(this).attr("checked",true);
});

This will do it, although i do agree this might be a bad idea.

Online example: http://jsfiddle.net/m5EuS/1/

UPDATE added group separation.

amosrivera
  • 26,114
  • 9
  • 67
  • 76
  • 1
    Make it "input.radio:checkbox" and you've got a deal. – Chris Tonkinson Jan 15 '11 at 04:13
  • this works, almost, the only part that does not work in the example is the fact that the names of the checkbox groups are different. In your code all the checkboxes on the page are affected, rather than those in a specific set. – superUntitled Jan 15 '11 at 04:17
  • 1
    no because that would still not work, if you notice the name, he's got 2 groups, you've got it acting as one big group – jondavidjohn Jan 15 '11 at 04:17
  • I had to add `.not(this)` to the group to get it working in my case - although I did hardcode in the name values to target a specific checkbox group: [http://jsfiddle.net/C3nw4/1/](http://jsfiddle.net/C3nw4/1/) – John Jul 10 '14 at 18:38
  • 1
    doesn't work with newer jQuery, use prop instead attr – st35ly Aug 14 '14 at 22:47
10

If you apply class to the checkbox, you can easily achieve the radio button functionality using the following piece of code:

$(".make_radio").click(function(){
    $(".make_radio").not(this).attr("checked",false); 
});
Pang
  • 9,564
  • 146
  • 81
  • 122
Waqas Ahmed
  • 311
  • 3
  • 6
9

Updated for Jquery 1.9 - use .prop() instead of .attr()

$("input:checkbox").click(function(){
    var group = "input:checkbox[name='"+$(this).prop("name")+"']";
    $(group).prop("checked",false);
    $(this).prop("checked",true);
});

Here is an example: http://jsfiddle.net/m5EuS/585/

Jake T.
  • 4,308
  • 2
  • 20
  • 48
user2301396
  • 91
  • 1
  • 1
4

Updated the script (via answer from Tomislav) so you also can uncheck ALL checkboxes. Just added a .not(this) and removed the line where the the current checkbox is checked.

$('form').each(function() { // iterate forms
  var $this = $(this);
  $this.find('input:checkbox').click(function() {
    var group = 'input:checkbox[name="' + $(this).attr('name') + '"]';
    $this.find(group).not(this).attr('checked', false).prop('checked', false); // also use prop, for real Property change
  });
});

http://jsfiddle.net/kya0639w/

Paintoshi
  • 816
  • 10
  • 12
3

basically the same answer as @amosrivera but remove the unchecking of all the checkbox as its necessary. instead use .not()

    $("input:checkbox").click(function(){
        var group = "input:checkbox[name='"+$(this).prop("name")+"']";
        $(group).not(this).prop("checked",false);
    });
Rob
  • 47
  • 4
3

Perhaps you want to consider a different approach. I believe you want to style the radio button to look like a checkbox. If so, see: this google search

And below is a simplified example that I borrow from www.thecssninja.com.

To put it simply: you hide the actual radio button (see the css input[type=radio]) and you style the label for the corresponding radio button to show the custom checkbox (from the css sprite in the background image in input[type=radio] + label) and switch to a different sprite in the background when the radio button is in checked state. Running example here: http://jsfiddle.net/jchandra/R5LEe/

    <!DOCTYPE html> 
    <html> 
    <head> 
      <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
      <title> Custom CSS3 control facade</title>       
      <style type='text/css'> 
        label {
          padding: 0 0 0 24px;
        }

        input[type=radio] { 
          padding:0;
          margin:0;
          width:16px;
          height:16px; 
          position:absolute;
          left:0;
          opacity:0
        }

        input[type=radio] + label {
          background:url(http://www.thecssninja.com/demo/css_custom-forms/gr_custom-inputs.png) 0 -1px no-repeat; 
          width:50px;
          height:16px;
        }

        input[type=radio]:checked + label {
          background-position:0 -81px;
        }
      </style>       
    </head> 
    <body> 
      Custom control images and concept from www.thecssninja.com<br/> 
      <br/> 
      <input type="radio" class="radio" value="1" name="fooby[1][]" id="r1" /><label for="r1"></label> 
      <input type="radio" class="radio" value="2" name="fooby[1][]" id="r2" /><label for="r2"></label> 
      <input type="radio" class="radio" value="3" name="fooby[1][]" id="r3" /><label for="r3"></label> 
      <br/> 
      <input type="radio" class="radio" value="1" name="fooby[2][]" id="r4" /><label for="r4"></label> 
      <input type="radio" class="radio" value="2" name="fooby[2][]" id="r5" /><label for="r5"></label> 
      <input type="radio" class="radio" value="3" name="fooby[2][]" id="r6" /><label for="r6"></label> 
  </body> 
</html>
Jimmy Chandra
  • 6,472
  • 4
  • 26
  • 38
1

Use change event of checkbox and assign checked value for current selected checkbox:

 $("input[type=checkbox]").change(function()
 {
  $("input[type=checkbox]").prop('checked',false);
  $(this).prop('checked',true);
 });
.checkBoxb{
  float:left;
  clear:both;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkBoxb"><input type="checkbox"  /> CheckBox1</label>
<label class="checkBoxb"><input type="checkbox"  /> CheckBox2</label>
<label class="checkBoxb"><input type="checkbox"  /> CheckBox3</label>
<label class="checkBoxb"><input type="checkbox"  /> CheckBox4</label>
0

I would comment but don't have the rep. Use .change, not .click for accessibility and so it works with the keyboard, like so:

  jQuery(".radio-check-box").change( function() {
    var checked = jQuery(this).prop("checked");
    jQuery(".radio-check-box").attr("checked", false);
    jQuery(this).prop("checked", checked);
  } );
Davorama
  • 76
  • 5
0

If you select "$("input:checkbox")" will select all the checkbox so you can specify the different radio button by using their name.

    $("[name='sname1']").click(function(){
     var group = "input:checkbox[name='"+$(this).attr("name")+"']";
     $(group).prop("checked",false);

Below Example will explain

 $("[name='sname1']").click(function(){
    var group = "input:checkbox[name='"+$(this).attr("name")+"']";
    $(group).prop("checked",false);
    $(this).prop("checked",true);
 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div style="border:1px solid">
<label><input type="checkbox" id="Titleblink_check" name="sname1">Blink</label>
&nbsp;&nbsp;(OR)&nbsp;&nbsp;
<label><input type="checkbox" id="Titleshine_check" name="sname1">Shine Text</label>
<br>
</div>



<label><input type="checkbox" id="id1" >Diff Check box1</label>
<br>
<label><input type="checkbox" id="id2">Diff Check box2</label>
<br>
<label><input type="checkbox" id="id3">Diff Check box3</label>
<br>

$(this).prop("checked",true); });

Merbin Joe
  • 611
  • 6
  • 27
0

I updated the Fiddle script, jQuery was missing. Now with prop and attr (use both).

$('form').each(function() { // iterate forms
  var $this = $(this);
  $this.find('input:checkbox').click(function() {
    var group = 'input:checkbox[name="' + $(this).attr('name') + '"]';
    $this.find(group).attr('checked', false).prop('checked', false); // also use prop, for real Property change
    $(this).attr('checked', true).prop('checked', true); // also use prop, for real Property change
  });
});

Fiddle

Pang
  • 9,564
  • 146
  • 81
  • 122
0

The solution given doesn't care about the initial state, which is different from the radio buttons behavior. Plus, it also triggers a change event when clicking on an already checked input.

var $elements = $('input:checkbox');

// Allow only one input to be selected
$elements.filter(':checked:not(:last)').prop('checked', false);

// Get selected input
var selected = $elements.filter(':checked')[0] || {};

// Handle event
$(document).on('click', 'input:checkbox', function(e) {
  if (e.currentTarget === selected) {
    e.preventDefault(); 
  } else {
    selected.checked = false;
    selected = e.currentTarget;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label><input type="checkbox" value="0" /> test 0</label>
<label><input type="checkbox" value="1" checked /> test 1</label>
<label><input type="checkbox" value="2" checked /> test 2</label>
<label><input type="checkbox" value="3" /> test 3</label>

I also agree that doing that is a bad idea, but if you have a different name for each input (and can't change them), there is no other choice...

gtournie
  • 4,143
  • 1
  • 21
  • 22