如何使用单选按钮选择singel和多个复选框

时间:2018-08-11 18:04:58

标签: javascript html

我陷入了这个问题。我有2个单选按钮和几个复选框。我想做的是,如果radiobutton1被选中,则只允许选中1复选框,然后,如果radiobutton2被选中,则将选中所有复选框。

我已经尝试过一些脚本,但是没有一个起作用。

这是我的示例代码。

HTML

<input type="radio" id="radio1" name="radiobtn1" />
<input type="radio" id="radio1" name="radiobtn2" />

<input type="checkbox" name="cb" value="1" onclick="test(this)" />
<input type="checkbox" name="cb" value="2" onclick="test(this)"/>
<input type="checkbox" name="cb" value="3" onclick="test(this)"/>
<input type="checkbox" name="cb" value="4" onclick="test(this)"/>
<input type="checkbox" name="cb" value="5" onclick="test(this)"/> 

仅选择1个复选框的脚本

function test(id){
    var cb = document.getElementsByName("cb");
    Array.prototype.forEach.call(cb,function(el){
      el.checked = false;
     });
        id.checked = true;
     }

我的脚本

$(function test(id){
$("#radio1, #radio2").change(function(){
    if($("#radio1").is(":checked")){
      var cb = document.getElementsByName("cb");
      Array.prototype.forEach.call(cb,function(el){
        el.checked = false;
      });
      id.checked = true;
    }
    else if($("#radio2").is(":checked")){

    }
});
});

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

就像您的问题已解决。 下次尝试先找到它。

但是您可以尝试使用此脚本。

var $form = $('#form1');
var $checkboxes = $('input[type=checkbox]');
var $selectionType = $('input[type=radio]');
var $output = $('#output');

// Used to determine if the Multi radio is selected
var isMulti = false;

// Listen to change event on the radio buttons and set isMulti
$selectionType.on('change', function( e ) {
// Check the value of what radio button was clicked
isMulti = $( e.target ).val() === 'Multi';

// Clear all selected checkboxes if user clicked "single"
if( !isMulti ) {
    $checkboxes.each( function( idx, item ) {
        $( item ).prop( 'checked', false );
    });
}
});

// Listen to clicks on checkboxes
$checkboxes.on('change', function( e ) {

// Store what was just clicked
var $this = $( e.target );

// If Multi is not selected, then remove the check from all checkboxes except
// the one that the user actually clicked on
if( !isMulti ) {

    $checkboxes.each( function( idx, item ) {

        var $item = $( item );

        if( $item.attr('id') === $this.attr('id') ) {
            return true;
        }

        $item.prop('checked', false );
    });
}
});

http://jsfiddle.net/grammar/pdx8gccu/2/