jQuery: make checkboxes act like radio buttons?
Asked Answered
A

11

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.

Afterclap answered 15/1, 2011 at 4:9 Comment(7)
Why not use actual radio buttons? Using checkboxes as radio buttons is going to confuse the hell out of your users.Conidium
I could dress my dog like a cat, but wouldn't it be smarter to just get a cat?Misesteem
@Phrogz: Was I not serious enough? :/Conidium
thanks for the fair warnings! i know this is a terrible idea. I have no excuse.Afterclap
@Conidium One cannot uncheck a radio button unlike a checkbox.Festschrift
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.Quickly
Problem is that it's hard to uncheck a radio button. I needed an either or control for a form so I naturally chose radio buttons but I also needed to de-select the radio button selection. But having a "select none" radio button was ugly and there was no clear or reasonable way to deselect that worked. So here I am exploring this lousy problem.Ventilate
S
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.

Shell answered 15/1, 2011 at 4:12 Comment(5)
Make it "input.radio:checkbox" and you've got a deal.Demythologize
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.Afterclap
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 groupMisesteem
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/Shend
doesn't work with newer jQuery, use prop instead attrIndispose
M
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); 
});
Maintain answered 16/10, 2014 at 10:19 Comment(2)
This is elegant usage of not method.Arredondo
This is more elegant than the other solution.Indohittite
O
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/

Operculum answered 20/4, 2013 at 5:33 Comment(0)
P
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/

Portiaportico answered 30/9, 2016 at 6:4 Comment(0)
C
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>
Cultus answered 15/1, 2011 at 4:24 Comment(0)
I
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);
    });
Illaudable answered 10/2, 2014 at 17:30 Comment(2)
this won't work as radio button, you need to set check on each time on clickIndispose
Thanks this helped me out to make it also uncheckable. Nice approch with the not function.Pasadena
A
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>
Aiaia answered 28/9, 2016 at 12:37 Comment(0)
G
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);
  } );
Gobbledygook answered 28/8, 2014 at 18:51 Comment(0)
M
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); });

Mcgary answered 20/5, 2015 at 10:1 Comment(0)
H
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

Hedgcock answered 27/5, 2016 at 20:37 Comment(0)
E
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...

Economically answered 30/3, 2017 at 0:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.