cucuru cucuru - 21 days ago 7
Javascript Question

attr value in table element

I have a table with attr wich I dont know how to get:

<ul id="myTable" >
<li><span data-myData="01">first value</span></li>
<li><span data-myData="02">second value</span></li>
</ul>
<button id = "myButton"> click me </button>


in jquery, when element is selected and clicking the button:

$(document).on('click', '#myButton', function() {
var tableLength = $('#myTable li').length;
for(var m=0; m<=tableLength; m++){
if($('#myTable li' + ":nth-child(" + (m+1) + ")").hasClass('selected')){
var valor = $('#myTable li' + ":nth-child(" + (m+1) + ")").text(); //works
var id = $('#myTable li' + ":nth-child(" + (m+1) + ")").attr("data-myData"); // doesnt work

}
}
});


How can I get the value

Answer

The main issue with your code is that the data attribute is on the span, not the li, hence your code returns undefined.

Also note that you can tidy your code up with the use of each() and the :gt selector to avoid the first li in the ul. Try this:

$(document).on('click', '#myButton', function() {
  $('#myTable li:gt(0)').each(function() {
    var $li = $(this);
    var valor = $li.text();
    var id = $li.find('span').data('mydata'); // note data() and lowercase property name
    
    console.log(valor);
    console.log(id);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul id="myTable">
  <li><span data-myData="01">first value</span></li>
  <li><span data-myData="02">second value</span></li>
  <li><span data-myData="03">third value</span></li>
</ul>
<button id="myButton">click me</button>

Comments