Neo Teo Neo Teo - 5 months ago 7
Javascript Question

How to pass text from view to javascript

Hi there i have problem with

Rails
&
Javascript
. Here is my table in view.

<table>
<thead>
<tr>
<th>No</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr id="adminrow">
<td>
1
</td>
<td>
<a href="#" id="select_name">John</a>
</td>
</tr>
<tr id="adminrow">
<td>
2
</td>
<td>
<a href="#" id="select_name">Alex</a>
</td>
</tr>
<tr id="adminrow">
<td>
3
</td>
<td>
<a href="#" id="select_name">Paul</a>
</td>
</tr>
</tbody>
</table>


and my
JS
is

$('#select_name').click(function(event){
var username = $("#select_name").text();
console.log(username);
});


I have lot of names in my table, but
JS
printed first name in console. How can I print each name in the table to console?

gen gen
Answer

You are creating in the each-loop N links (by the number of users) with the same select_name ID. Your javascript is confused, which one to choose. Try to add user id to your html select_name id and adjust your javascript accordingly. Same about your other id adminrow.

OR simply change your select_name to be a class and not id:

 ....
 %a{:href=>"#", :class=>"select_name"}=u.firstname
 ....
 $('.select_name').click(function(event){ ....

Ok, I am attaching the full code for you. For me it works just fine. E.g. prints just the name after clicking on the corresponding link:

<table>
<thead>
  <tr>
    <th>No</th>
    <th>Name</th>
  </tr>
</thead>
<tbody>
    <tr class="adminrow">
      <td>
        1
      </td>
      <td>
        <a href="#" class="select_name">John</a>
      </td>
    </tr>
    <tr class="adminrow">
      <td>
        2
      </td>
      <td>
        <a href="#" class="select_name">Alex</a>
      </td>
    </tr>
    <tr class="adminrow">
      <td>
        3
      </td>
      <td>
        <a href="#" class="select_name">Paul</a>
      </td>
    </tr>
</tbody>
</table>

<script type="text/javascript">
  $('.select_name').click(function(event){
    var username = $(this).text();
    console.log(username);
  });
</script>
Comments