0

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>

2
  • Your code works as I would expect it to but I am guessing your are looking for different results. Maybe give us an example of how it should be different? Commented Dec 23, 2017 at 7:22
  • Infront of red checkbox only red should display. But in my code all checked are displaying. Commented Dec 23, 2017 at 7:24

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.