繁体   English   中英

jQuery不适用于仅选择一个复选框

[英]jQuery not working for select only one 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元素不是兄弟姐妹,因为它们的父元素不同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);

小提琴1


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

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

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

小提琴2

这样做会不会简单得多

var checkBoxes = $('input[type=checkbox]');
$('table').on('click', 'input[type=checkbox]', function () {
  checkBoxes.prop('checked', false);
  $(this).prop('checked', true);
});

而且在tr内有一个div

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM