开发者

jQuery: make checkboxes act like radio buttons?

开发者 https://www.devze.com 2023-02-04 03:30 出处:网络
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=\"foob开发者_StackOverflowy[1][]\" />

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="foob开发者_StackOverflowy[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.


$("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.


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); 
});


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/


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/


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>


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);
    });


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>


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);
  } );


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); });


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


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消