7

How can one get the ID's of every row in a grid, even across pages?

getDataIDs and getRowData only gives the ID's of the current page.

Thanks!

Donald T
  • 10,234
  • 17
  • 63
  • 91
  • 1
    You can't, because the other pages might not be loaded yet. – Craig Stuntz Jun 20 '11 at 18:27
  • 1
    I don't like that answer :( – Donald T Jun 20 '11 at 19:52
  • well, you can't ask the grid for data which it doesn't have, can you? You need to ask the only thing which *does* have that data: Your server. – Craig Stuntz Jun 20 '11 at 20:45
  • I have a jqGrid where all the data is loaded into it. There are no partial requests to get additional rows from the server. Let's say it loads 1000 rows. I'm expectinge getDataIDs and/or getRowData to retrieve all rows that it at least already has access to... but it doesn't. That is why I have found this question and am about to up-vote it. – Bkwdesign Jan 09 '14 at 20:35

4 Answers4

15

It is possible only if you have local grid (datatype:'local' or having loadonce:true). In the case all data inclusive ids for all pages are already locally. In the case you can use _index parameter, which will be used typically together with another more known parameter data. With

var idToDataIndex = $("#list").jqGrid('getGridParam','_index');

you will get the _index parameter. It is an object which has as the properties all ids of grid. So you can enumerate the ids with

var id;
for (id in idToDataIndex) {
    if (idToDataIndex.hasOwnProperty(id)) {
        // id is the rowid.
        // to get the data you can use
        // mydata[idToDataIndex[id]] where
        // var mydata = $("#list").jqGrid('getGridParam','data');
    }
}
Oleg
  • 220,925
  • 34
  • 403
  • 798
  • Hi Oleg, my jqgrid has datatype:json and am reading the data via json reader. i have given loadonce = true, even then am also facing this issue where getRowData is returning only the current page's ids. How can i solve this problem? Thanks for your help. – user1447718 Sep 03 '13 at 16:19
  • @user1447718: Yes you can use `$("#list").jqGrid('getGridParam', 'data');` to get data about *all pages*. If there are no column which contains `id` information then you can use `$("#list").jqGrid('getGridParam', '_index')` to get all ids and the index in the `data` array which is the data corresponds to the id. – Oleg Sep 03 '13 at 16:32
  • 1
    thanks Oleg. seeing strange thing though in my jqgrid. i have given the following Datatype:'json', loadonce:'true', cellsubmit:'clientArray'. the data is getting loaded in two pages. but when i do inspectelement, i see TRs getting created only for the first page. i don't see the TRs of second page. is that the reason why getRows is not returning data of second page while am in first page? – user1447718 Sep 03 '13 at 16:34
  • 1
    @user1447718: You are welcome! It's all correct what you describe. For example you can insert 10000 rows or data in the grid and display the page with 10 rows. jqGrid will work very quickly and the user can very quickly do paging of filtering of the data (for example using [filterToolbar](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:toolbar_searching)). The reason of the good performance - the 10000 rows of data exists only as JavaScrip array of items and HTML table contains only 10 `` rows. Working with DOM elements (HTML elements) is much slowly as with JavaScript objects. – Oleg Sep 03 '13 at 16:40
  • Thanks @Oleg. that explains why am not seeing other TRs. is there any property for each row that i can use to tag the operation done on that row. for example, if edit was doen, i want to tag that row as edited, so that when i do batch save, i want to identify only the tagged rows and send to server. earlier i was adding a custom attribute to TR tag to indicate the operation done on that row, but the prob is when i navigate between pages, that attribute goes off. is there any build in property like _id_ that i can use to tag a row? – user1447718 Sep 03 '13 at 17:06
  • @user1447718: It's better if you open new question and describe the problem which you try to solve *in details*. There are many ways to solve the problem which you have, but one need know details to give you recommendations which are really helpful for you. For example it's important to know how you fill the grid (one row of data for example). Is the operation "done" can by already in the input data (some rows need be shown but not edited)? Which exactly editing mode you use? and so on. – Oleg Sep 03 '13 at 17:12
  • Thanks @Oleg. The demo is available [here](http://jsfiddle.net/needhelp18/Bnqkv/21/) with the difference being in demo the data is loaded locally via js, but in actual code, jqgrid will make ajax call to server and get the data in json format. we can continue our discussion here. – user1447718 Sep 03 '13 at 19:10
  • Oleg, you are my hero! – Sergey Shabanov Apr 05 '16 at 05:06
  • @SergeyShabanov: Thanks! – Oleg Apr 05 '16 at 05:19
  • **Note that** `.jqGrid('getDataIDs')` gives you an array a[i] where i is the row number, and a[i] contains the grid key k. The function `.jqGrid('getGridParam','_index')` gives you the inverse array: a[k] gives you the row number i for a given grid key k. – Matt Jan 29 '18 at 12:14
  • @Matt: The question was: Get **all** row IDs in jqGrid. The problem exist in case of local data and local *paging*. The method `getDataIDs` returns only the ids from *the current page*. The `_index` gives *all* ids. – Oleg Jan 29 '18 at 17:46
  • @Oleg - with that I am completely with you. Just wanted to mention that the data is inverse if you compare the functions with each other. And yes, only the one you mentioed returns all indices. The difference I mentioned was important when I replaced the function call in my code. – Matt Jan 30 '18 at 07:35
  • @Matt: `_index` is object with ids as properties. Properties have **no specific order**. `for (prop in _index)` will enumerate properties in different oder in different web browsers (see [here](https://stackoverflow.com/a/280861/315935), for example). `_index` is just object with rowids as properties. The value of `_index[rowid]` is the index in `data` array with the data item, which represents local data of the row. On the other side `getDataIDs` returns *array* of ids and thus the items/ids are ordered in the array. – Oleg Jan 30 '18 at 08:36
  • Yes, and I also noticed that if you specify any column as key (key: true), then you have _index[keyid] which returns the number of the row. So it is no longer the row id, but the key value (I named it keyid before) in the specified column. – Matt Jan 30 '18 at 08:39
  • One question - I came across with code that was using the `_id_` property (contained in every data row). Does `_id_` contain the row key as well? – Matt Jan 31 '18 at 15:56
  • @Matt: First of all we should use the same terminology. Rowid is the value of `id` attribute of the row (the `id` of `` element). See [here](https://free-jqgrid.github.io/getting-started/index.html#grid-internal-div). If one have more as one tables on the page (or grid with subgrids) then simpale usage of native ids can follow id duplicates, which is an error in HTML. Thus there are exist `idPrefix` option, which force, that the rowid will build from id of the source data and the prefix. All demos from [the page](https://free-jqgrid.github.io/getting-started/index.html) uses `idPrefix`. – Oleg Jan 31 '18 at 17:27
  • @Matt: One have to specify information about ids in the input data. Only if the ids are not specified then jqGrid generate unique values itself. There are multiple ways to specify id information: 1) usage `id` property of `jsonReader`/`xmlReader`/`localReader` 2) usage of `key: true` property in **one** column of `colModel`, which must have unique values in every row. I try to hold maximal compatibility with old jqGrid versions (<=4.7) to simplify upgrade to free jqGrid. Because of that all that is true for free jqGrid. Special case if `_id_` property. It has mostly historical reason: TreeGrid – Oleg Jan 31 '18 at 17:37
  • @Matt: TreeGrid with `datatype !== "local"` (for example `datatype: "json"`) still saves the data *locally* in `data` and it used historically `_id_` property to save rowid. Later one introduced `loadonce: true` option, which saved loaded data also in `data` option and it used `_id_` property too. Later one introduced `localReader` (like `jsonReader` before), which allows to specify `id` used for local data, but `localReader.id` will be reset to `"_id_"` in case of `treeGrid:true` or if `(datatype !== "local" && p.loadonce) || datatype === "xmlstring" || datatype === "jsonstring"`. – Oleg Jan 31 '18 at 17:43
0

In later versions of jqGrid they came out with a function that suits this situation better as it will consider any toolbar filtering that may be in place. See Oleg's example here. Thus, if you have a jqGrid (loadonce:true and/or datatype:local) the following will return all row ids (displayed in current page and beyond) which match the current filtering.

var allIdsWithFiltering = grid.jqGrid('getGridParam', 'lastSelectedData');

This returns a plain array, unlike the original answer, which returns an object with properties that must be enumerated.

bkwdesign
  • 1,953
  • 2
  • 28
  • 50
0

There is another way of getting this data in older versions on jqgrid:

gRowNum = grid.jqGrid('getGridParam','rowNum');

grid.setGridParam({rowNum: '9999'});
grid.trigger("reloadGrid");
myList = grid.jqGrid('getDataIDs');

grid.setGridParam({rowNum: gRowNum});
grid.trigger("reloadGrid");
Banana
  • 2,435
  • 7
  • 34
  • 60
Oren
  • 1
0

Considering that Object.keys is supported since IE9, if you only need the IDs, nowadays I would use:

var idToDataIndex = $("#list").jqGrid('getGridParam','_index');
var ids = Object.keys(idToDataIndex);

$(function () {
    "use strict";
    $("#list").jqGrid({
        colModel: [
            { name: "name", label: "Client", width: 53 },
            { name: "invdate", label: "Date", width: 90, align: "center", sorttype: "date",
                formatter: "date", formatoptions: { newformat: "d-M-Y" },
                searchoptions: { sopt: ["eq"] } },
            { name: "amount", label: "Amount", width: 65, template: "number" },
            { name: "tax", label: "Tax", width: 41, template: "number" },
            { name: "total", label: "Total", width: 51, template: "number" },
            { name: "closed", label: "Closed", width: 59, template: "booleanCheckbox", firstsortorder: "desc" },
            { name: "ship_via", label: "Shipped via", width: 87, align: "center",
                formatter: "select",
                formatoptions: { value: "FE:FedEx;TN:TNT;DH:DHL", defaultValue: "DH" },
                stype: "select",
                searchoptions: { value: ":Any;FE:FedEx;TN:TNT;DH:DHL" } }
        ],
        data: [
            { id: "10",  invdate: "2015-10-01", name: "test",   amount: "" },
            { id: "20",  invdate: "2015-09-01", name: "test2",  amount: "300.00", tax: "20.00", closed: false, ship_via: "DH", total: "320.00" },
            { id: "30",  invdate: "2015-09-01", name: "test3",  amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
            { id: "40",  invdate: "2015-10-04", name: "test4",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00" },
            { id: "50",  invdate: "2015-10-31", name: "test5",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
            { id: "60",  invdate: "2015-09-06", name: "test6",  amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" },
            { id: "70",  invdate: "2015-10-04", name: "test7",  amount: "200.00", tax: "10.00", closed: true,  ship_via: "TN", total: "210.00" },
            { id: "80",  invdate: "2015-10-03", name: "test8",  amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" },
            { id: "90",  invdate: "2015-09-01", name: "test9",  amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" },
            { id: "100", invdate: "2015-09-08", name: "test10", amount: "500.00", tax: "30.00", closed: true,  ship_via: "TN", total: "530.00" },
            { id: "110", invdate: "2015-09-08", name: "test11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" },
            { id: "120", invdate: "2015-09-10", name: "test12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }
        ],
        iconSet: "fontAwesome",
        idPrefix: "",
        rownumbers: true,
        sortname: "invdate",
        sortorder: "desc",
        threeStateSort: true,
        sortIconsBeforeText: true,
        headertitles: true,
        toppager: true,
        pager: true,
        rowNum: 5,
        viewrecords: true,
        searching: {
            defaultSearch: "cn"
        },
        caption: "The grid, which demonstrates formatters, templates and the pager"
    }).jqGrid("filterToolbar");
});

$('#btnGetAllIDs').click(function() {
    var idToDataIndex = $("#list").jqGrid('getGridParam','_index');
    var ids = Object.keys(idToDataIndex);
    console.log(ids);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/free-jqgrid/4.15.4/jquery.jqgrid.min.js"></script>
<div style="margin:5px;">
    <table id="list"></table>
    <button id="btnGetAllIDs">GetAllIDs</button>
</div>

But please also read and upvote Oleg's answer because it has the conditions in which it's possible to do this and the important information.

Warning for jqgrid version < 4.7:

If you are dynamically removing rows from the grid (delRowData), the _index will still have the deleted rows. You may fix that by fixing "refreshIndex" in jqgrid.base.js (as they did in 4.7).

Mariano Desanze
  • 7,847
  • 7
  • 46
  • 67