javascriptjqueryscalatwirl

How to collect an array of HTML elements that have the same ID using jQuery?


I'm using the Scala Play Framework, Twirl and jQuery.

I have a dynamic table of rows dependent upon how much data is in a model:

<table>
  @for(i <- someDataModel){ //play form containing several fields
    <tr id="dataRow">@i.name</tr> //display the name field string
  }
</table>

I want to collect all of the values in these rows, and add them to an array in order to process them in jQuery for a CSV export.

I've attempted to collect the data using jQuery:

$('#dataRow').filter(function () { 
  var array = [];
  var getData = $('[id="' + this.id + '"]').text(); //get all rows
  var i;
  for (i = 0; i < x.length; ++i) {
    alert(x[i]) //pop up on screen with each value found
    array.push(x[i]) //add to the array
  }
});

The above code does find all row values, but it collects all string names at once, merges them all together into a single string, then iterates through each character. So it's almost there, but I just need the values to be whole.

My question is how do I iterate through all of this data separately and add them to an array when all rows have the same ID?


Solution

  • How about instead of doing this:

    var getData = $('[id="' + this.id + '"]').text();
    

    You do something like this:

    var getData = $('[id="' + this.id + '"]').each(function(){
        var value = $(this).text();
        alert(value);
        array.push(value)
    });
    

    People in the comments are right you need to use classes. You can then just use .className instead of selecting the id attribute, but in this case it wouldn't really matter. You do not really want to have more than 1 unique ID ever, if you do, then you are doing it wrong.