Setting data attribute on each row of a jqgrid table
Asked Answered
V

2

10

I am using jqGrid and I'm trying to add a data- attribute to each tr. I'm firing the loadComplete event, but I'm unsure of how to modify each row. Any code samples?

Vigil answered 16/8, 2013 at 19:56 Comment(2)
Can't you use a custom formatter for that cell?Oliver
I want it on the tr itself - not the cell.Vigil
C
13

You can use rowattr to assign any additional attribute to <tr> elements (see the answer and this one for code examples). For example you can use

rowattr: function (rd) {
    return {"data-mydata": JSON.stringify(rd)};
}

to save full input row data as data-mydata attribute. I recommend you to use rowattr``in combination withgridview: true` option to have the best performance results ()

The demo uses above rowattr cade and you can see that rows of grid have additional data-mydata attribute:

enter image description here

Crimmer answered 19/8, 2013 at 11:53 Comment(1)
How would I handle spaces? When I do the following: return { "data-delete-name": rd.name }; and rd.name has a space, it only includes the first word.Vigil
O
0

In my cases, I set the first column of grid by an identity. And in all my cases, id of each data row of my grids is the value of that identity column.

jqGrid column:

colModel: [
{
name:'ID',
label:'...',
width:1,
index:'ID'
...

Rendered :

<tr role="row" id="10777" ... > // in retrieved data: ID = 10777

So, if you have similar declarations like me, this could be a useful selector for you and you can simply add your data- attrib to these rows like this:

$('#trId').prop('data-whatever', 'value');

And if you want the above line to be performed automatically to all rows, you should change it slightly and put it into the gridComplete event of your grid:

gridComplete: function() { $("tr[role='row']").prop('data-whatever', 'value'); }
Oliver answered 16/8, 2013 at 20:48 Comment(3)
Sure, having the ID there is very helpful. However, I still have other data elements that I would like to place in a data attribute on the row. I know jqGrid has other ways to get at that data, but I'm changing out a custom grid for a jqGrid so there's existing functionality/styles that I'm still trying to take advantage of.Vigil
But where do I put that selector? In the loadComplete event? And how do I call it?Vigil
Great, now how would I append values from the dataset?Vigil

© 2022 - 2024 — McMap. All rights reserved.