0

I have a table that looks like this with many more columns (the number is context-dependent).

    $('.action-checkbox').val(
        $(this).parent().parent().find(".col-record_id").first().text().trim()
    )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody>
        <tr>
            <td>
                <input type="checkbox" name="rowid" class="action-checkbox">
            </td>
            <td class="col-record_id">
            10
            </td>
        </tr>
        <tr>
            <td>
                <input type="checkbox" name="rowid" class="action-checkbox">
            </td>
            <td class="col-record_id">
            14
            </td>
        </tr>
    </tbody>

But this sets an empty value.

What am I doing wrong?

Thanks in advance.

1
  • 2
    You are not giving val() a callback method. You are just executing a statement. As such, the value of this is going to be whatever it is within the context of where the $('.action-checkbox') is called, rather than referring to each element found. Commented Aug 15, 2018 at 16:05

1 Answer 1

2

You need to pass a callback function to .val() in order to assign a value to it, returning a value. Like this:

$('.action-checkbox').val(function() {
  return $(this).parent().next().text().trim()
})

or this using .each()

$('.action-checkbox').each(function() {
  $(this).val($(this).parent().next().text().trim())
})

$('.action-checkbox').val(function() {
  return $(this).parent().next().text().trim()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="checkbox" name="rowid" class="action-checkbox">
    </td>
    <td class="col-record_id">
      10
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" name="rowid" class="action-checkbox">
    </td>
    <td class="col-record_id">
      14
    </td>
  </tr>
</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.