javascript - jQuery 不适用于只选择一个复选框

标签 javascript jquery html checkbox

我建立了一个四行八列的表格,每列都有一个复选框。我希望每行只允许检查一个复选框。我正在尝试使用 jquery 来执行此操作。从逻辑上讲,它在 jsfiddle 中有效,但对我来说在本地不起作用。我确实首先使用了警报来确保首先加载 jQuery。

下面是我的代码。问题是,我仍然可以在每行中选中多个复选框,而我应该只允许选中一个复选框:

 <body>
    <h2>Checkbox Test</h2>
    <script type="text/javascript" src="http://localhost/mytesting/jquery-2.1.4.js"></script>
    <script type="text/javascript">

    function onLoadAlert() {
        alert('Sup');
    }

    $(document).ready(onLoadAlert);
    </script>

    <script type="text/javascript">
        $('input[type="checkbox"]').on('change', function() {

          // uncheck sibling checkboxes (checkboxes on the same row)
          $(this).siblings().prop('checked', false);

          // uncheck checkboxes in the same column
          $('div').find('input[type="checkbox"]:eq(' + $(this).index() + ')').not(this).prop('checked', false);

        });
    </script>

    <table border="1">

    <tbody>
    <tr>
        <th><b>COST</b></th>
        <th colspan="3">Reduced Cost</th>
        <th>Neutral</th>
        <th colspan="3">Increased Cost</th>
        <th>Don't Know</th>
    </tr>
    <tr>
        <th></th>
        <th>High</th>
        <th>Medium</th>
        <th>Low</th>
        <th>No effect</th>
        <th>Low</th>
        <th>Medium</th>
        <th>High</th>
        <th></th>
    </tr>
    <tr>
        <td>Capital cost</td>
        <div>
        <td><input type="checkbox" id="matrix1" value="1"></td>
        <td><input type="checkbox" id="matrix2" value="1"></td>
        <td><input type="checkbox" id="matrix3" value="1"></td>
        <td><input type="checkbox" id="matrix4" value="1"></td>
        <td><input type="checkbox" id="matrix5" value="1"></td>
        <td><input type="checkbox" id="matrix6" value="1"></td>
        <td><input type="checkbox" id="matrix7" value="1"></td>
        <td><input type="checkbox" id="matrix8" value="1"></td>
        </div>

    </tr>



    </tbody>

最佳答案

您的 input 元素不是 sibling ,因为它们有不同的父元素 – td 元素:

<td><input type="checkbox" id="matrix1" value="1"></td>
<td><input type="checkbox" id="matrix2" value="1"></td>

这就是为什么这不起作用:

$(this).siblings().prop('checked', false);

相反,这样做:

$(this).closest('tr').find('input').not(this).prop('checked', false);

Fiddle 1


或者,您可以使用具有相同 name 的单选按钮:

 <td><input type="radio" name="matrix"></td>
 <td><input type="radio" name="matrix"></td>
 <td><input type="radio" name="matrix"></td>

这样,您就不需要任何 JavaScript。

Fiddle 2

关于javascript - jQuery 不适用于只选择一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248846/

相关文章:

javascript - 在 Chrome 中,页面不会在 Ajax 加载后调整大小

html - css 网格增长超过 100% 宽度与 fr 但不是与 minmax

javascript - 等待javascript递归函数返回true

php - 如何在 jQuery 代码中转义 "["字符

php - 需要用PHP保存数据的HTML表单

JavaScript 无法在 IE 和 Chrome 中运行

php - 了解 "post/redirect/get"模式

php - 在 HTML 表中显示 MySQL 查询

javascript - 使用 Phaser 制作迷宫的平铺 map 编辑器

javascript - 带有 react.js 的编译文件太大