Take data-Cod element value

Asked

Viewed 125 times

2

How do I get the value of the data-Cod element?

$(document).ready(function() {

  $('.chatUsuariosLista').click(function() {
    $("#para").val(this.id);


  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="1" data-cod="21321321" class="row chatUsuariosLista">Nome 1</div>

<div id="2" data-cod="54654655" class="row chatUsuariosLista">Nome 2</div>

<div id="3" data-cod="79879878" class="row chatUsuariosLista">Nome 3</div>

<br>

<input id="para" type="text" value="">
<input id="projeto" type="text" value="">

1 answer

2


You have to use the API .data() jQuery, or the native .dataset.

With jQuery it would be: var data = $(this).data('cod');
With native Javascript it would be: var data = this.dataset.cod;

$(document).ready(function() {
  $('.chatUsuariosLista').click(function() {
    $("#para").val(this.dataset.cod);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="1" data-cod="21321321" class="row chatUsuariosLista">Nome 1</div>
<div id="2" data-cod="54654655" class="row chatUsuariosLista">Nome 2</div>
<div id="3" data-cod="79879878" class="row chatUsuariosLista">Nome 3</div>
<br>
<input id="para" type="text" value="">
<input id="projeto" type="text" value="">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.