Looping jquery get value from the button and put on the label

0

My dear ones,

I have a table of users, and for each user I have a button that opens a modal:

{% for item in lista_usuarios %}
    <tr>
        <td>{{ item.first_name }}</td>

        <button data-target="modal1" class = "oi" type = "button" value="{{item.id}}"  class = "btn waves-effect waves-light blue" data-index="{{item.id}}" onclick="$('#modal1').modal('open');" >
            <i class="large material-icons">clear</i>
        </button>
        </td>
    </tr>

As you can see, the value of this button is already taking the id of each user, this is correct.

In the modal, I have a label and I need the value of this id to be passed to it.

 <input type="text" class="usuario">

<script>

    $(document).ready(function(){
        $(".oi").each(function() {
            $(this).click(function() {
                alert("teste");
                $('.modal').modal();
                var id = $(".oi").val();
                alert(id);
                $(".usuario").val(id);
            });
        });
    });


</script>

Modal is running and 2 alerts as well. However, it is passing the same user id always, passing only the id of the first user to the label within the modal.

    
asked by anonymous 25.10.2017 / 15:39

1 answer

1

I do not see a need to use $.each in this case. Follow the example below and implement to your reality that it will work.

$(document).ready(function(){
  $('body').on ('click', 'table > tbody > tr > td button.oi', function (ev) {
    console.log ($(this).val());
  });
    
});

var openModal = function () {
  console.log ('Executando openModal.');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><tbody><tr><td>item10</td><td><buttondata-target="modal1" class = "oi" type = "button" value="10"  class = "btn waves-effect waves-light blue" data-index="10" onclick="openModal();" >
          <i class="large material-icons">clear</i>
        </button>
      </td>
    </tr>
    <tr>
      <td>item 20</td>
      <td>
        <button data-target="modal1" class = "oi" type = "button" value="20"  class = "btn waves-effect waves-light blue" data-index="20" onclick="openModal();" >
          <i class="large material-icons">clear</i>
        </button>
      </td>
    </tr>
    <tr>
      <td>item 30</td>
      <td>
        <button data-target="modal1" class = "oi" type = "button" value="30"  class = "btn waves-effect waves-light blue" data-index="30" onclick="openModal();" >
          <i class="large material-icons">clear</i>
        </button>
      </td>
    </tr>
  </tbody>
</table>
    
25.10.2017 / 16:29