0

Once page load is completed, I am looking for table cells which contain elements (number input fields) with an id of "check_status". I then loop over them (example simplified to a console.log).

Coffeescript

ready = ->
  $('td').find('#check_status').each (i, el) =>
    console.log el.val()
  return

$(document).ready(ready);
$(document).on('page:load', ready);

HTML

<td>
    <div>
        <input type="number" value="1" name="check[status]" id="check_status">
    </div>
</td>
<td>
    <div>
        <input type="number" value="0" name="check[status]" id="check_status">
    </div>
</td>
<td>
    <div>
        <input type="number" value="2" name="check[status]" id="check_status">
    </div>
</td>

Console.log of $('td').find('#check_status') gives me all the elements I am looking for, but console.log of el.val() gives "el is not defined". Why?

Wilco van Esch
  • 457
  • 1
  • 7
  • 17
  • 5
    IDs must be unique on document context... – A. Wolff Nov 22 '15 at 14:20
  • 2
    And `el` is DOM node, not jq object. Use `el.value` or `$(el).val();` or use `this` but not `el.val()`. – A. Wolff Nov 22 '15 at 14:22
  • `"el is not defined"` Which browser gives you this error, because that's not the case. `el` is defined but `val` property isn't – A. Wolff Nov 22 '15 at 14:25
  • Chrome. Thanks, I'd overlooked the unique IDs entirely. I'm using Rails and these duplicate IDs are because every input field is generated in a separate form_for. I will add some unique identifier to the IDs, then return to this. – Wilco van Esch Nov 22 '15 at 14:32

3 Answers3

0

Id's should be unique. You should change id="check_status" to class="check_status" and the selection to find('.check_status').

omer
  • 26
  • 2
0

Have you tried the .each() with a function inside?
Like this:

$('td').find('#check_status').each (function (i, el){
  console.log (el.val())
});
Bianca S.
  • 84
  • 4
0

The culprit ended up being this (snippet from Rails 4: how to use $(document).ready() with turbo-links):

$(document).ready(ready);
$(document).on('page:load', ready);

ready = ->
    ... function contents ...

Not quite sure why that made the each in the ready function fail, but it works fine when I instead use:

$(document).ready ->
    ... function contents ...
Community
  • 1
  • 1
Wilco van Esch
  • 457
  • 1
  • 7
  • 17