簡體   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