I am trying to get the value of a table cell.
For example
<table id='projects'>
<tr>
<td id='a'>aaaaa</td>
<td id='b'>bbbbb</td>
<td id='c'>ccccc</td>
<td id='d'>eeeee</td>
<td id='e'>ddddd</td>
</tr>
</table>
<a id='test' href='#'>test </a>
I want to get aaaaa,bbbbb,ccccc,eeeee,ddddd and assign them to my array
I believe I can get the value with my Jquery code below
$(document).ready(function(){
$('#test').click(function(){
var tableVal=new Array();
tableVal['a']=$('#a').text();
tableVal['b']=$('#b').text();
tableVal['c']=$('#c').text();
tableVal['d']=$('#d').text();
tableVal['e']=$('#e').text();
})
});
However, I think it's not very maintainable and take lots of code if I have 20 tags. I was wondering if I can do it with .each
or any better way to archive this. Thanks for the help.
If you actually want an Array, use .map()
with .toArray()
.
var tableVal = $('#projects td').map(function(i,v) {
return $(this).text();
}).toArray();
Otherwise if you're actually going to use non numeric indices, you want an Object, using the techniques in the other answers.
You can do something like below,
var tableVal= [];
$('#projects tr:eq(0) td').each (function () {
tableVal[this.id] = $(this).text();
});
Note: :eq(0) - means 1st row.. Modify accordingly if you want to do for all rows or let me know if you need help with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With