Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
选中复选框时,使用javascript取消选中其他复选框_Javascript_Checkbox - Fatal编程技术网

选中复选框时,使用javascript取消选中其他复选框

选中复选框时,使用javascript取消选中其他复选框,javascript,checkbox,Javascript,Checkbox,我用ADODB.Recordset填充表格。我有25排。但它可以改变。最后一列是复选框 只能选择一个复选框。选中一个,取消选中其他自动 <input class="cb" id="txtdurum_<%=counter%>" name="txtdurum" type="checkbox" /> 请提供帮助:)您可以使用jQuery: $('.cb').change(function(){ $('.cb').prop('checked',false);

我用ADODB.Recordset填充表格。我有25排。但它可以改变。最后一列是复选框

只能选择一个复选框。选中一个,取消选中其他自动

<input class="cb" id="txtdurum_<%=counter%>" name="txtdurum" type="checkbox" />

请提供帮助:)

您可以使用jQuery:

$('.cb').change(function(){
   $('.cb').prop('checked',false);
   $(this).prop('checked',true); 
});
这会将更改侦听器添加到具有“cb”类属性的所有复选框中。 将该代码片段放入jqueryready函数中

例如:

更新1: 如果还希望启用,则用户可以取消选中所有:

$('.cb').change(function(){
    var checkState = $(this).prop('checked');
    $('.cb').prop('checked',false);
    $(this).prop('checked', checkState);
});
例如:

但是:
最好使用单选按钮,试试下面的代码。在每个输入复选框中添加一个
onchange
事件

<input class="cb" id="txtdurum_<%=counter%>" name="txtdurum" type="checkbox" onchange="check(this)"/>

JS:

功能检查(元素){
如果(元素已选中){
var复选框=document.getElementsByClassName('cb');
对于(var i=0;i,虽然我强烈建议您使用
type=“radio”
元素(如果需要的话,可以使用“不选择任何内容”选项),但我非常感兴趣,花了最后几个小时来整理这种方法

这是一种方法,感觉有点过头了,也没有我想要的那么流线型,但它足以满足您的需求。我为介绍提供了一个简单的演示,JavaScript自始至终都有评论:

var Limit = (function () {
    // private to this function, but shared by all instances:

    // simple 'closest' function;
    // start: DOM Node,
    // needle: String, the tagName of the ancestor to find.

    // if no ancestor exists (we stop at the <body> element)
    // function returns null:
    var closest = function (start, needle) {
        // we begin at the 'start' node, but use
        // the 'current' variable as a pointer as
        // we move through the ancestors:
        var current = start,

            // converting the tagName to lower-case,
            // for predictable comparisons:
            find = needle.toLowerCase();

        // while the tagName of the current element-node is not
        // what we're looking for AND the current element-node is
        // not the <body> element:
        while (current.tagName.toLowerCase() !== find && current.tagName.toLowerCase() !== 'body') {
            // we set the current node to its parentNode,
            // thereby ascending through the DOM:
            current = current.parentNode;
        }

        // if the tagName of the current element-node is 'body'
        // we return null, otherwise we return that current node:
        return current.tagName.toLowerCase() === 'body' ? null : current;
    };

    return function (groupSelector) {
        // protected variables, available on a
        // per-instance basis:

        // the array in which we'll hold the selected
        // <input> elements as they're checked:
        var checked = [],

            // the group of elements to which this instance
            // will apply:
            group = document.querySelectorAll(groupSelector),

            // the defaults:
            // allowInvalidity, Boolean:
            //    true:  allows the user to select more than
            //           the maximum number of choices.
            //    false: prevents the selection of options
            //           beyond the maxumum number.
            // fifo, Boolean:
            //    true:  should the user try to select more
            //           than the maximum number of choices
            //           the first element in the array is
            //           removed.
            //    false: should the user try to select more
            //           than the maximum number of choices
            //           subsequent choices are prevented.
            // maxChoices, Number:
            //           defines the maximum number of choices
            //           that can be made.
            // parentErrorClass, String:
            //           the class-name to be applied to the
            //           parent of the <input> elements when
            //           the user chooses more than the maximum
            //           number of options (requires
            //           settings.invalidity to be true).

            defaults = {
                'allowInvalidity': false,
                    'fifo': true,
                    'maxChoices': 1,
                    'parentErrorClass': 'error'
            };

        // the object containing the function(s) we
        // make available:
        return {

            // opts is the user-defined settings
            // passed in:
            'nOnly': function (opts) {

                // a simple, though potentially costly,
                // means of avoiding JavaScript's
                // pass-by-reference (which prevents
                // settings = dafaults from working),
                // here creating a copy via the JSON functions:
                var settings = JSON.parse(JSON.stringify(defaults));

                // iterating over the user-defined settings in the
                // supplied opts object:
                for (var setting in opts) {

                    // avoiding iterating over inherited properties
                    // from the Object.prototype:
                    if (opts.hasOwnProperty(setting)) {

                        // setting the settings options to
                        // those supplied in the opts object:
                        settings[setting] = opts[setting];
                    }
                }

                // iterating over the Array-like NodeList returned by
                // document.querySelectorAll() (when we retrieved the
                // nodes for this 'group'), using Function.prototype.call()
                // to apply Array.prototype.forEach():
                Array.prototype.forEach.call(group, function (input) {
                    // there are three arguments available to
                    // Array.prototype.forEach(), the names are
                    // user-defined (within variable-naming constraints);
                    // the first (here: 'input') the current array-element
                    // from the array over which we're iterating,
                    // the second (not used) is the index of that array-element,
                    // the third (not used) is the full array over which
                    // we iterate.

                    // here we bind the anonymous function as the 'change'
                    // event-handler on each of the <input> elements in
                    // the parent group:
                    input.addEventListener('change', function (event) {

                        if (input.checked && settings.allowInvalidity === false) {
                            // add the <input> to the checked array:
                            checked.push(input);

                            // if too many choices have been made:
                            if (checked.length > settings.maxChoices) {

                                // we call Array.prototype.pop() (if
                                // settings.fifo is true) or
                                // Array.prototype.shift() (if
                                // settings.fifo is not exactly-true)
                                // to select the first element of the
                                // checked Array (shift()) or the last
                                // element (pop()) and set that element's
                                // checked property to false. Using shift()
                                // or pop() also removes it from the array:
                                checked[settings.fifo === true ? 'shift' : 'pop']().checked = false;
                            }

                        } else if (input.checked && settings.allowInvalidity === true) {
                            // we simply add the <input> to the array:
                            checked.push(input)
                        } else {

                            // we test that the <input> element is in
                            // the checked Array:
                            if (checked.indexOf(input) > -1) {

                                // using Array.prototype.splice() to
                                // remove it from the Array; using
                                // Array.prototype.indexOf() (again) 
                                // to retrieve its index in the Array:
                                checked.splice(checked.indexOf(input), 1);
                            }
                        }

                        // iterating over the group, with Array.prototype.forEach():
                        Array.prototype.forEach.call(group, function (input) {

                            // if the <input> is not checked, or the number of choices
                            // is less than the permitted maximum:
                            if (!input.checked || checked.length <= settings.maxChoices) {

                                // we remove the parentErrorClass from the parentNode:
                                input.parentNode.classList.remove(settings.parentErrorClass);

                                // otherwise if the <input> is checked, AND
                                // there are too many choices:
                            } else if (input.checked && checked.length > settings.maxChoices) {

                                // we add the parentErrorClass to the parentNode:
                                input.parentNode.classList.add(settings.parentErrorClass);
                            }
                        });

                    });
                });
            }
        };
    };
})();

new Limit('.group1 input').nOnly({
    'allowInvalidity': true,
        'maxChoices': 3
});
new Limit('.group2 input').nOnly({
    'maxChoices': 1,
        'fifo': false
});
new Limit('.group3 input').nOnly({
    'allowInvalidity': true,
    'maxChoices' : 2,
    'parentErrorClass' : 'oops'
});

第一组
输入1
输入2
投入3
输入4
输入5
第2组
输入1
输入2
投入3
输入4
输入5
第3组
输入1
输入2
投入3
输入4
输入5

您应该使用
type=“radio”
对于这些,因为这是单选按钮的默认功能。但是用户,没有什么可以选择。用户也可以选择没有。为了提供“没有”选项,复选框的使用情况仍然是错误的。@EmrahŞentürk查看我的答案。我更新了我的代码,因此用户也可以取消选中所有复选框。您排除了IE8兼容性th
document.getElementsByClassName('cb');
,如果您使用了
document.queryselectoral('cb')
,那么,这(应该)与IE*及以上版本兼容。错误:未定义或无法获取属性空引用“markedI”。此代码有效。但我使用getElementsById和其他方法代替getElementsByClassName。谢谢。
var Limit = (function () {
    // private to this function, but shared by all instances:

    // simple 'closest' function;
    // start: DOM Node,
    // needle: String, the tagName of the ancestor to find.

    // if no ancestor exists (we stop at the <body> element)
    // function returns null:
    var closest = function (start, needle) {
        // we begin at the 'start' node, but use
        // the 'current' variable as a pointer as
        // we move through the ancestors:
        var current = start,

            // converting the tagName to lower-case,
            // for predictable comparisons:
            find = needle.toLowerCase();

        // while the tagName of the current element-node is not
        // what we're looking for AND the current element-node is
        // not the <body> element:
        while (current.tagName.toLowerCase() !== find && current.tagName.toLowerCase() !== 'body') {
            // we set the current node to its parentNode,
            // thereby ascending through the DOM:
            current = current.parentNode;
        }

        // if the tagName of the current element-node is 'body'
        // we return null, otherwise we return that current node:
        return current.tagName.toLowerCase() === 'body' ? null : current;
    };

    return function (groupSelector) {
        // protected variables, available on a
        // per-instance basis:

        // the array in which we'll hold the selected
        // <input> elements as they're checked:
        var checked = [],

            // the group of elements to which this instance
            // will apply:
            group = document.querySelectorAll(groupSelector),

            // the defaults:
            // allowInvalidity, Boolean:
            //    true:  allows the user to select more than
            //           the maximum number of choices.
            //    false: prevents the selection of options
            //           beyond the maxumum number.
            // fifo, Boolean:
            //    true:  should the user try to select more
            //           than the maximum number of choices
            //           the first element in the array is
            //           removed.
            //    false: should the user try to select more
            //           than the maximum number of choices
            //           subsequent choices are prevented.
            // maxChoices, Number:
            //           defines the maximum number of choices
            //           that can be made.
            // parentErrorClass, String:
            //           the class-name to be applied to the
            //           parent of the <input> elements when
            //           the user chooses more than the maximum
            //           number of options (requires
            //           settings.invalidity to be true).

            defaults = {
                'allowInvalidity': false,
                    'fifo': true,
                    'maxChoices': 1,
                    'parentErrorClass': 'error'
            };

        // the object containing the function(s) we
        // make available:
        return {

            // opts is the user-defined settings
            // passed in:
            'nOnly': function (opts) {

                // a simple, though potentially costly,
                // means of avoiding JavaScript's
                // pass-by-reference (which prevents
                // settings = dafaults from working),
                // here creating a copy via the JSON functions:
                var settings = JSON.parse(JSON.stringify(defaults));

                // iterating over the user-defined settings in the
                // supplied opts object:
                for (var setting in opts) {

                    // avoiding iterating over inherited properties
                    // from the Object.prototype:
                    if (opts.hasOwnProperty(setting)) {

                        // setting the settings options to
                        // those supplied in the opts object:
                        settings[setting] = opts[setting];
                    }
                }

                // iterating over the Array-like NodeList returned by
                // document.querySelectorAll() (when we retrieved the
                // nodes for this 'group'), using Function.prototype.call()
                // to apply Array.prototype.forEach():
                Array.prototype.forEach.call(group, function (input) {
                    // there are three arguments available to
                    // Array.prototype.forEach(), the names are
                    // user-defined (within variable-naming constraints);
                    // the first (here: 'input') the current array-element
                    // from the array over which we're iterating,
                    // the second (not used) is the index of that array-element,
                    // the third (not used) is the full array over which
                    // we iterate.

                    // here we bind the anonymous function as the 'change'
                    // event-handler on each of the <input> elements in
                    // the parent group:
                    input.addEventListener('change', function (event) {

                        if (input.checked && settings.allowInvalidity === false) {
                            // add the <input> to the checked array:
                            checked.push(input);

                            // if too many choices have been made:
                            if (checked.length > settings.maxChoices) {

                                // we call Array.prototype.pop() (if
                                // settings.fifo is true) or
                                // Array.prototype.shift() (if
                                // settings.fifo is not exactly-true)
                                // to select the first element of the
                                // checked Array (shift()) or the last
                                // element (pop()) and set that element's
                                // checked property to false. Using shift()
                                // or pop() also removes it from the array:
                                checked[settings.fifo === true ? 'shift' : 'pop']().checked = false;
                            }

                        } else if (input.checked && settings.allowInvalidity === true) {
                            // we simply add the <input> to the array:
                            checked.push(input)
                        } else {

                            // we test that the <input> element is in
                            // the checked Array:
                            if (checked.indexOf(input) > -1) {

                                // using Array.prototype.splice() to
                                // remove it from the Array; using
                                // Array.prototype.indexOf() (again) 
                                // to retrieve its index in the Array:
                                checked.splice(checked.indexOf(input), 1);
                            }
                        }

                        // iterating over the group, with Array.prototype.forEach():
                        Array.prototype.forEach.call(group, function (input) {

                            // if the <input> is not checked, or the number of choices
                            // is less than the permitted maximum:
                            if (!input.checked || checked.length <= settings.maxChoices) {

                                // we remove the parentErrorClass from the parentNode:
                                input.parentNode.classList.remove(settings.parentErrorClass);

                                // otherwise if the <input> is checked, AND
                                // there are too many choices:
                            } else if (input.checked && checked.length > settings.maxChoices) {

                                // we add the parentErrorClass to the parentNode:
                                input.parentNode.classList.add(settings.parentErrorClass);
                            }
                        });

                    });
                });
            }
        };
    };
})();

new Limit('.group1 input').nOnly({
    'allowInvalidity': true,
        'maxChoices': 3
});
new Limit('.group2 input').nOnly({
    'maxChoices': 1,
        'fifo': false
});
new Limit('.group3 input').nOnly({
    'allowInvalidity': true,
    'maxChoices' : 2,
    'parentErrorClass' : 'oops'
});