Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting multiple elements' text with Jquery

Tags:

arrays

jquery

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.

like image 941
FlyingCat Avatar asked Jan 29 '12 22:01

FlyingCat


2 Answers

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.

like image 50
user1106925 Avatar answered Oct 02 '22 18:10

user1106925


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.

like image 37
Selvakumar Arumugam Avatar answered Oct 02 '22 20:10

Selvakumar Arumugam