jQuery - checkboxes like radiobuttons

前端 未结 9 1602
小鲜肉
小鲜肉 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:43

    Why don't you use radio buttons, then?

    The difference is there for a reason. It has been designed this way, and from a user perspective radio buttons mean "select one", and checkboxes mean "select many".

    Don't break user's expectations by changing this well-tried paradigm. It's a bad thing when application developers prefer "looks" over usability and convention, so don't be one of them.

    User interfaces work because the metaphors used (checkboxes, buttons, the shape of the mouse pointer, colors, etc.) are and behave a certain way. Users will have problems with your app and may not even know why when you do things like this.

    This is an anti-pattern that falls into the same category as changing the label with the checkbox state:

    [ ] enable option        vs.      [ ] option
    [x] disable option                [x] option
    
    0 讨论(0)
  • 2020-12-01 11:44
    var $unique = $('input.unique');
    
    $unique.click(function() {
    
     $checked = $(this).is(':checked') ; // check if that was clicked.
     $unique.removeAttr('checked'); //clear all checkboxes
     $(this).attr('checked', $checked); // update that was clicked.
    
    });
    
    0 讨论(0)
  • 2020-12-01 11:44

    Based on the primitive behaviour of "radio buttons group" that only one radio button can be selected within the same group, "radio buttons approach" is always preferred than "checkboxes approach", because it can help preventing anomalous data submission in the event of JavaScript or jQuery coding cannot be loaded properly.

    Then, the only challenge for us to solve is to make the selected radio button be 'de-selectable'.

    So, here is an example to show that, by using additional JavaScript control, radio buttons still can be de-selected. This example has used jQuery as the main JavaScript framework.

    Online version is also available in JSFiddle.net: http://jsfiddle.net/0fbef3up/

    This example has considered to cater for a contingency scenario in case JavaScript or jQuery coding does not load, and so a 'contingent option item' is provided. In order to see how will be such special scenario and how does the contingency work, you can simply omit the loading of the jQuery library by comment/delete the relevant line of code:

    <script type='text/javascript' src='http://code.jquery.com/jquery-2.1.4.min.js'></script>
    

    Below is the full HTML/JavaScript code for demonstration. The essence is at the JavaScript function 'selectiongrp_logicControl', you may study it for reference.

    JavaScript (i.e., control/model layer) at the first coding frame and HTML (i.e. presentation layer) at the second coding frame:

    function selectiongrp_logicControl( s_selectiongrpName, b_useJQueryUiThemeToDecorate )
    {
    	// Safeguard measure: If the mandatory function parameter is undefined or empty, nothing can be proceed further, so quit the current function with excit code:
    	if ( !s_selectiongrpName ) return -1;
    
    
    	// Define a constant for future use:
    	var ADF_THIS_IS_LAST_SELECTED='adf_this-is-last-selected';
    
    	// Hide the 'contingent select option item' and all its relevant ancillary objects (i.e. the label element):
    	$( '#' + s_selectiongrpName + '-option-X' ).hide();
    	$( '#' + s_selectiongrpName + '-option-X' ).next( 'label' ).hide();
    
    	// Decorate the selection group option items and their labels by applying the jQueryUI 'buttonset' function:
    	if( b_useJQueryUiThemeToDecorate )   $( '#jQueryUi-' + s_selectiongrpName).buttonset();
    
    	// Loop for each option item within the selection group:
    	$( 'input[name=' + s_selectiongrpName + ']' ).each( function()
    	{
    		// Define an 'onClick' event for every option item within the selection group:
    		$( this ).on( 'click', function()
    		{
    			// If the option item being clicked is the last selected one, then de-select such item.
    			// Two ways can achieve de-selection, apply either one below to adapt to your programming style or desired controller mechanism.
    
    			if( $( this ).attr( ADF_THIS_IS_LAST_SELECTED ) )
    			{
    				// Way[1]: Force selecting another item within the same selection group.
    				// This Way entails the 'contingent select option item'.  So, if you consider such 'contingent select option item' is unnecessary/inappropriate to your programming style or controller mechanism, please don't choose this Way.
    				// (Note: Such 'contingent select option item' was deliberately hidden at the outset).
    				// $( '#' + s_selectiongrpName + '-option-X' ).prop( 'checked', true );
    
    				// Way[2]: Simply remove the current item's "checked" attribute:
    				$( this ).removeAttr( 'checked' );
    
    				// Both Way[1] and Way[2]: Remove the additional attribute from the item being clicked.
    				$( this ).removeAttr( ADF_THIS_IS_LAST_SELECTED );
    			} else
    			{
    				// Apply an additional attribute to the item being clicked.  This additional attribe functioned as a secret hint for internal reference to signify the item was the last seledcted one:
    				$( this ).attr( ADF_THIS_IS_LAST_SELECTED, ADF_THIS_IS_LAST_SELECTED );
    			}
    			// Other than the item being clicked, all other items (i.e. denotes by the jQuery 'not( this )' selector) should have removed such additional attribute:
    			$( 'input[name=' + s_selectiongrpName + ']' ).not( this ).removeAttr( ADF_THIS_IS_LAST_SELECTED );
    
    			// Force the jQueryUI engine to re-render the decoration to reflect the latest selection by applying the 'buttonset' function again ( provide the 'refresh' parameter ):
    			if( b_useJQueryUiThemeToDecorate )   $( '#jQueryUi-' + s_selectiongrpName ).buttonset( 'refresh' );
    
    			// Lastly, this is an optional step, refresh the Result Area for displaying user's latest selection on specific screen area:
    			selectiongrp_visualControl_refreshResultArea( s_selectiongrpName );
    		});
    	});
    }
    
    
    
    function selectiongrp_visualControl_refreshResultArea( s_selectiongrpName )
    {
    	// Safeguard measure: If the mandatory function parameter is undefined or empty, nothing can be proceed further, so quit the current function with excit code:
    	if( !s_selectiongrpName )   return -1;
    
    
    	var adf_resultArea_string;
    	var ADF_RESULTAREA_STRING_NOTHING_SELECTED='Nothing is selected';
    
    	// If Way[1] is adopted:
    	if( $( '#' + s_selectiongrpName + '-option-X' ).prop( 'checked' ) )
    	{
    		adf_resultArea_string=ADF_RESULTAREA_STRING_NOTHING_SELECTED;
    	} else // If Way[2] is adopted:
    	{
    		// If some option items are selected within the selection group:
    		if( $( 'input[name=' + s_selectiongrpName + ']:checked' ).length > 0 )
    		{
    			adf_resultArea_string='You have selected : [' + $( 'input[name=' + s_selectiongrpName + ']:checked' ).next( 'label' ).text() + ']';
    		} else
    		{
    			adf_resultArea_string=ADF_RESULTAREA_STRING_NOTHING_SELECTED;
    		}
    	}
    
    	$( '#fieldset-' + s_selectiongrpName + '-resultarea' ).html( adf_resultArea_string );
    	$( '#fieldset-' + s_selectiongrpName + '-result' ).show();
    }
    
    $( document ).ready( function()
    {
    	var ADF_USE_JQUERYUI_THEME_TO_DECORATE=true;
    	selectiongrp_logicControl( 'selectiongrp-01', !ADF_USE_JQUERYUI_THEME_TO_DECORATE );
    	selectiongrp_logicControl( 'selectiongrp-02', ADF_USE_JQUERYUI_THEME_TO_DECORATE );
    
    	// If jQuery can be loaded properly, the error message must be hidden:
    	$( '#jquery-compatibility-error' ).hide();
    });
    <!-- 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.min.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.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/ui-darkness/jquery-ui.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/blitzer/jquery-ui.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/eggplant/jquery-ui.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/flick/jquery-ui.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css'/>
    <link rel="stylesheet" type="text/css" href='http://code.jquery.com/ui/1.11.4/themes/sunny/jquery-ui.min.css'/>
    -->
    <link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.11.4/themes/redmond/jquery-ui.min.css'>
    
    
    This webpage is primarily to demonstrate de-selectable radio boxes.
    
    <h3 id='jquery-compatibility-error'>ERROR: It was detected that JavaScript or jQuery coding does not load properly, so some advance feature cannot be realised.</h3>
    
    <h3>Style1: Raw (i.e. no 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='X' id='selectiongrp-01-option-X' checked/><label for='selectiongrp-01-option-X'>None/NULL/Non-Selected <small><small>(This option is provided for contingency purpose in case JavaScript or jQuery does not load)</small></small></label>
    		<input type='radio' name='selectiongrp-01' value='Y' id='selectiongrp-01-option-Y'/><label for='selectiongrp-01-option-Y'>Yes</label>
    		<input type='radio' name='selectiongrp-01' value='N' id='selectiongrp-01-option-N'/><label for='selectiongrp-01-option-N'>No</label>
    		<input type='radio' name='selectiongrp-01' value='U' id='selectiongrp-01-option-U' /><label for='selectiongrp-01-option-U'>Unknown</label>
    	</span>
    </fieldset>
    <fieldset id='fieldset-selectiongrp-01-result' style='display:none'>  <!-- Initaially hidden by using stylesheet attribute "style='display:none'"-->
    	<legend>Selection</legend>
    	<span id='fieldset-selectiongrp-01-resultarea'><br/></span>
    </fieldset>
    
    <br/>
    
    <h3>Style2: Decorated by &quot;jQueryUI Theme&quot; <small><small>(jQueryUI Theme adopted: '<i>Redmond</i>')</small></small>:</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='X' id='selectiongrp-02-option-X' checked/><label for='selectiongrp-02-option-X'>None/NULL/Non-Selected <small><small>(This option is provided for contingency purpose in case JavaScript or jQuery does not load)</small></small></label>
    		<input type='radio' name='selectiongrp-02' value='Y' id='selectiongrp-02-option-Y'/><label for='selectiongrp-02-option-Y'>Yes</label>
    		<input type='radio' name='selectiongrp-02' value='N' id='selectiongrp-02-option-N'/><label for='selectiongrp-02-option-N'>No</label>
    		<input type='radio' name='selectiongrp-02' value='U' id='selectiongrp-02-option-U' /><label for='selectiongrp-02-option-U'>Unknown</label>
    	</span>
    </fieldset>
    <fieldset id='fieldset-selectiongrp-02-result'style='display:none;'>  <!-- Initaially hidden by using stylesheet attribute "style='display:none'"-->
    	<legend>Selection</legend>
    	<span id='fieldset-selectiongrp-02-resultarea'><br/></span>
    </fieldset>

    0 讨论(0)
提交回复
热议问题