jQuery - checkboxes like radiobuttons

前端 未结 9 1601
小鲜肉
小鲜肉 2020-12-01 11:07

I have group checkboxes and I like if this group have behaviour like radiobuttons with same name atribute.

Each checkbox has different name.

Only one can be

相关标签:
9条回答
  • 2020-12-01 11:21

    Pablo's answer works great if you only have one set of these on your page. I came across this when attempting to workaround a bootstrap implementation that was giving me some trouble because radio buttons had been completely overwritten and it turns out it will be easier to just use the checkboxes as radio buttons.

    Here's a version of this code that allows multiple sets by referencing the calling element's second class.

    $('input.unique').each(function() {
      $(this).on('touchstart click', function() {
        var secondClass = $(event.target).attr('class').split(' ')[1];
        $('input.' + secondClass).not(this).removeAttr('checked');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <input type='checkbox' name='mygroup1' value='1' class='unique check1'>
    <input type='checkbox' name='mygroup2' value='2' class='unique check1'>
    <input type='checkbox' name='mygroup3' value='3' class='unique check1'>
    <br>
    <hr>
    <input type='checkbox' name='mygroup1' value='1' class='unique check2'>
    <input type='checkbox' name='mygroup2' value='2' class='unique check2'>
    <input type='checkbox' name='mygroup3' value='3' class='unique check2'>

    JSFiddle

    0 讨论(0)
  • 2020-12-01 11:23
    $(".checkboxClass").click(function() {
        $(".checkboxClass").each(function() {
            $(this)[0].checked = false;});
        $(this)[0].checked = true;
    });
    

    First clear all checkboxes, then check the one that was clicked.

    0 讨论(0)
  • 2020-12-01 11:26

    This live demo illustrates Radio Button can perform what you desired:

    http://jsfiddle.net/ftnwg8yf/

    function selectiongrp_control( s_selectiongrpName, b_useJQueryUiThemeToDecorate )
    {
    	var ADF_THIS_IS_LAST_SELECTED_ATTR='adf_this-is-last-selected-attr'
    	var ADF_THIS_IS_LAST_SELECTED_VALUE='adf_this-is-last-selected-val';
    
    	if ( !s_selectiongrpName ) return -1;
    
    	$( '#fieldset-' + s_selectiongrpName + '-result' ).hide();
    	if( b_useJQueryUiThemeToDecorate )   $( '#jQueryUi-' + s_selectiongrpName).buttonset();
    
    	$( 'input[name=' + s_selectiongrpName + ']' ).each( function()
    	{
    		$( this ).on( 'click', function()
    		{
    			if( $( this ).attr( ADF_THIS_IS_LAST_SELECTED_ATTR ) )
    			{
    				$( this ).removeAttr( 'checked' );
    				$( this ).removeAttr( ADF_THIS_IS_LAST_SELECTED_ATTR );
    			} else
    			{
    				$( this ).attr( ADF_THIS_IS_LAST_SELECTED_ATTR, ADF_THIS_IS_LAST_SELECTED_VALUE );
    			}
    
    			$( 'input[name=' + s_selectiongrpName + ']' ).not( this ).removeAttr( ADF_THIS_IS_LAST_SELECTED_ATTR );
    			if( b_useJQueryUiThemeToDecorate )   $( '#jQueryUi-' + s_selectiongrpName ).buttonset( 'refresh' );
    
    			if( $( 'input[name=' + s_selectiongrpName + ']:checked' ).length > 0 )
    			{
    				$( '#fieldset-' + s_selectiongrpName + '-resultarea' ).html( 'You have selected : [' + $( this ).val() + '].');
    			} else
    			{
    				$( '#fieldset-' + s_selectiongrpName + '-resultarea' ).html( 'Nothing is selected.' );
    			}
    			$( '#fieldset-' + s_selectiongrpName + '-result' ).show();
    		});
    	});
    }
    
    $( document ).ready( function() {
    	var ADF_USE_JQUERYUI_THEME_TO_DECORATE=true;
    	selectiongrp_control( 'selectiongrp-01', !ADF_USE_JQUERYUI_THEME_TO_DECORATE );
    	selectiongrp_control( 'selectiongrp-02', ADF_USE_JQUERYUI_THEME_TO_DECORATE );
    });
    <!-- Load jQuery core library -->
    <script type='text/javascript' src='http://code.jquery.com/jquery-2.1.4.min.js'></script>
    
    <!-- Load jQueryUI library-->
    <script type='text/javascript' src='http://code.jquery.com/ui/1.11.4/jquery-ui.js'></script>
    
    <!-- Load jQueryUI Theme library (make either one effective) -->
    <!--
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/ui-darkness/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/blitzer/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/eggplant/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/flick/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css'>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/sunny/jquery-ui.css'>
    -->
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/redmond/jquery-ui.css'>
    
    
    
    <h3>Plain (without styling/decoration):</h3>
    <fieldset id='fieldset-selectiongrp-01'>
    	<legend>Please <b>click</b> to <b>select</b> or <b>re-click</b> to <b>deselect</b> </legend>
    	<span id='jQueryUi-selectiongrp-01'>
    		<input type='radio' name='selectiongrp-01' value='Yes' id='selectiongrp-01-option-Y'/><label for='selectiongrp-01-option-Y'>Yes</label>
    		<input type='radio' name='selectiongrp-01' value='No' id='selectiongrp-01-option-N'/><label for='selectiongrp-01-option-N'>No</label>
    		<input type='radio' name='selectiongrp-01' value='Unknown' id='selectiongrp-01-option-U' /><label for='selectiongrp-01-option-U'>Unknown</label>
    	</span>
    </fieldset>
    <fieldset id='fieldset-selectiongrp-01-result'>
    	<legend>Result</legend>
    	<span id='fieldset-selectiongrp-01-resultarea'></span>
    </fieldset>
    
    <br/>
    
    <h3>Decorated by &quot;jQueryUI Theme&quot;:</h3>
    <fieldset id='fieldset-selectiongrp-02'>
    	<legend>Please <b>click</b> to <b>select</b> or <b>re-click</b> to <b>deselect</b> </legend>
    	<span id='jQueryUi-selectiongrp-02'>
    		<input type='radio' name='selectiongrp-02' value='Yes' id='selectiongrp-02-option-Y'/><label for='selectiongrp-02-option-Y'>Yes</label>
    		<input type='radio' name='selectiongrp-02' value='No' id='selectiongrp-02-option-N'/><label for='selectiongrp-02-option-N'>No</label>
    		<input type='radio' name='selectiongrp-02' value='Unknown' id='selectiongrp-02-option-U' /><label for='selectiongrp-02-option-U'>Unknown</label>
    	</span>
    </fieldset>
    <fieldset id='fieldset-selectiongrp-02-result'>
    	<legend>Result</legend>
    	<span id='fieldset-selectiongrp-02-resultarea'></span>
    </fieldset>

    0 讨论(0)
  • 2020-12-01 11:34

    I had a similar problem. I couldn't use radio button because the same form had to display multiple choice checkboxes in some situations. I took your markup and wrote this small piece of jQuery:

    $("span.multiGroup input").click(function() {
        $("span.multiGroup input").attr('checked', false);
        $(this).attr('checked', true);
    });
    
    0 讨论(0)
  • 2020-12-01 11:36

    HTML

    <input type='checkbox' name='mygroup1' value='1' class='unique'>
    <input type='checkbox' name='mygroup2' value='2' class='unique'>
    <input type='checkbox' name='mygroup3' value='3' class='unique'>
    

    Javascript

    $('input.unique').each(function() {
        $(this).on('touchstart click', function() {
        $('input.unique').not(this).removeAttr('checked');
    });
    });
    

    Fiddle: http://jsfiddle.net/L2ad1vd8/

    0 讨论(0)
  • 2020-12-01 11:41

    Here's a hint: Use radio buttons. ;)

    I wouldn't recommend doing this because it would be considered bad for usability and would certainly violate the principle of least surprise. Users have been conditioned to expect radios to accept 1 check and checkboxes to accept many. Don't make your users think.

    If you have your reasons, though, here's how to go about doing this with jQuery:

    <input type='checkbox' name='mygroup1' value='1' class='unique'>
    <input type='checkbox' name='mygroup2' value='2' class='unique'>
    <input type='checkbox' name='mygroup3' value='3' class='unique'>
    

    And the jQuery:

    var $unique = $('input.unique');
    $unique.click(function() {
        $unique.filter(':checked').not(this).removeAttr('checked');
    });
    

    And here's a live sample.

    EDIT:

    As pointed out in the comments, this would allow the user to deselect all checkboxes even if they chose one initially, which isn't exactly like radio buttons. If you want this, then the jQuery would look like this:

    var $unique = $('input.unique');
    $unique.click(function() {
        $unique.removeAttr('checked');
        $(this).attr('checked', true);
    });
    
    0 讨论(0)
提交回复
热议问题