Reputation: 850
I like to get the value of this attribute data-record-key
, but I use this line it's return me undefined
, Any help?
$("#testtable").find("tbody tr").attr("data-record-key")
<table id ="testtable">
<tbody>
<tr data-record-key="0">
<td>ALL</td></tr>
<tr data-record-key="1">
<td>ONE</td></tr>
</tbody>
</table>
Upvotes: 1
Views: 1252
Reputation: 3171
You will get the value of the attribute by using:;
jQuery("#testtable tbody tr").attr("data-record-key")
But I'm not sure what you are trying to obtain. You will read the first value only, and a table is supposed to have many rows, right?
If what you want is to get the selected value, you can use:
jQuery("#testtable tbody tr.selected").attr("data-record-key")
Upvotes: 1
Reputation: 56539
No need of using .attr instead use .data()
$("#testtable").find("tbody tr").each(function () {
console.log($(this).data("record-key"));
});
Updated with .each() to fetch for all td
, helps to iterate the object.
Upvotes: 1
Reputation: 64536
Your code produces undefined
because you aren't wrapping it in the DOM ready function. That means your code executes before the table element is available in the DOM. Change to:
$(document).ready(function(){
$("#testtable").find("tbody tr").data("record-key");
});
.data()
should be used instead of .attr()
for this, but that won't cause your code to return undefined, it should still work (as long as you use the DOM ready).
Also, if you want to get all of the data-record-key
's instead of just the first, you'll need a loop:
$(document).ready(function(){
$.each($("#testtable").find("tbody tr"), function(i, val){
console.log( $(this).data('record-key') );
});
});
Upvotes: 1
Reputation: 20270
You could just directly select the elements with data-record-key
, and get their values:
$(document).ready(function() {
var recordKeys = $('[data-record-key]').map(function() {
return $(this).data('recordKey');
}).get();
console.log(recordKeys); // outputs: [0, 1]
});
Upvotes: 1
Reputation: 12705
The .attr() method gets the attribute value for only the first element in the matched set. you should change your code.
$("#testtable").find("tbody tr").map(function(i){
return $(i).attr("data-record-key")
})
Upvotes: 1