user5836176 user5836176 - 6 months ago 112
HTML Question

Display multiple checkbox value in table

I am working on a project where I have to display check boxes and its values in a table. That means in one Column Checkbox s will be there and and next column i have to display its value. I am very new to

jquery
so I tried but not getting proper output.



$('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>




H77 H77
Answer Source

You're setting the value to all table cells that have the class hello. You should instead select only the one next to the checkbox. You can do this by navigating to the parent cell and then the next cell.

One way to do this would be $(this).parent().next(".hello")

e.g.

$('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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download