在表格中显示多个复选框值

问题描述 投票:0回答:1

我正在进行一个项目,我必须在表格中显示复选框及其值。这意味着在一个列中,复选框将存在,而下一列我必须显示其值。我是jquery的新手,所以我试过但没有得到正确的输出。

$('input[type=checkbox]').on('change', function() {
  if ($(this).is(':checked')) {
    var values = [];
    $.each($('input:checked'), function(index, input) {
      values.push(input.value);
    });

    var str = values.join(',');
    $(".hello").html(str);

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>checkboxes</th>
    <th>Values</th>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="red" class="theClass" />red
    </td>
    <td class="hello"></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="green" class="theClass" />green
    </td>
    <td class="hello"></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="blue" class="theClass" />blue
      <p></p>
    </td>
    <td class="hello"></td>
  </tr>

</table>

<table>
javascript jquery html
1个回答
1
投票

您将值设置为具有类hello的所有表格单元格。您应该只选择复选框旁边的那个。你可以通过navigating to the parent cellnext cell来做到这一点。

一种方法是$(this).parent().next(".hello")

EG

$('input[type=checkbox]').on('change', function() {
  var val = this.checked ? this.value : "";
  $(this).parent().next(".hello").text(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>checkboxes</th>
    <th>Values</th>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="red" class="theClass" />red
    </td>
    <td class="hello"></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="green" class="theClass" />green
    </td>
    <td class="hello"></td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name='cbox' value="blue" class="theClass" />blue
      <p></p>
    </td>
    <td class="hello"></td>
  </tr>

</table>

<table>
© www.soinside.com 2019 - 2024. All rights reserved.