raouf
raouf

Reputation: 585

How to get a jqGrid cell value when editing

How to get a jqGrid cell value when in-line editing (getcell and getRowData returns the cell content and not the actuall value of the input element).

Upvotes: 34

Views: 157713

Answers (24)

Post Impatica
Post Impatica

Reputation: 16463

I needed the original value before the formatter, so this is what I did:

{
    name: 'Slot', title: false, formatter: function (cellValue, options, rowObject) {
        rowObject['SlotID'] = cellValue;  // <--- This saves the original ID
        if (somelogic) {
            return someString;
        } else {
            return someOtherString;
        }
    }
},
{ name: 'SlotID', hidden: true }

Now SlotID contains the original ID. Also, you don't need to have SlotID property on your original model.

Upvotes: 0

Ignacio
Ignacio

Reputation: 131

I obtain edit value using javascript:

document.getElementById('idCell').value

I hope this info useful for someone.

Upvotes: 0

Pradeep nain
Pradeep nain

Reputation: 47

Before i was getting : html tag of the textbox something like

but Here is the solution to get the value from that particular column, working and tested

function getValue(rowId, cellId) {
        var val = $("[rowId='"+rowId+"'][name='"+cellId+"']").val();
        return val;
       }

var values = getValue(rowId, 'cellid');

Upvotes: 0

Pawel
Pawel

Reputation: 18272

General function to get value of cell with given row id and cell id

Create in your js code function:

function getCellValue(rowId, cellId) {
    var cell = jQuery('#' + rowId + '_' + cellId);        
    var val = cell.val();
    return val;
}

Example of use:

var clientId = getCellValue(15, 'clientId');

Dodgy, but works.

Upvotes: 17

AabinGunz
AabinGunz

Reputation: 12347

Try this, it will give you particular column's value

onSelectRow: function(id) {
    var rowData = jQuery(this).getRowData(id); 
    var temp= rowData['name'];//replace name with you column
    alert(temp);
}

Upvotes: 3

zaheerprince
zaheerprince

Reputation: 13

its very simple write code in you grid.php and pass the value to an other page.php
in this way you can get other column cell vaue

but any one can make a like window.open(path to pass value....) in fancy box or clor box?

$custom = <<<CUSTOM
jQuery("#getselected").click(function(){

    var selr = jQuery('#grid').jqGrid('getGridParam','selrow'); 
    var kelr = jQuery('#grid').jqGrid('getCell', selr, 'stu_regno');
    var belr = jQuery('#grid').jqGrid('getCell', selr, 'stu_school');
    if(selr) 

     window.open('editcustomer.php?id='+(selr), '_Self');


    else alert("No selected row");
    return false;
});

CUSTOM;
$grid->setJSCode($custom); 

Upvotes: 1

timbrown
timbrown

Reputation: 572

In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.

var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents)); 
//in my case logs <h3><a href="#">The Value I'm After</a></h3>

var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"

my answer is based on @LLQ answer, but since in my case my cellContents isn't an input I needed to use .text() instead of .val() to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.

Upvotes: 1

Mitul Maheshwari
Mitul Maheshwari

Reputation: 2647

You can get it from the following way...!!

var rowId =$("#list").jqGrid('getGridParam','selrow');  
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId'];   // perticuler Column name of jqgrid that you want to access

Upvotes: 1

user2066558
user2066558

Reputation: 11

I have a solution: 1. Using this.value to get the current editing value in the editing row. 2. Save the cell value to a hidden field when the cell lost its focus. 3. Read the hidden field when you need.

The code:

 colModel="[
       { name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
       { name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
    ]" 

Good Luck

Upvotes: 1

LLQ
LLQ

Reputation: 29

Hi, I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.

My solution like this:

var userIDContent = $("#grid").getCell(id,"userID");  // Use getCell to get the content
//alert("userID:" +userID);  // you can see the content here.

//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val();  // var userID = $(userIDContent).attr('attrName');

Upvotes: 2

hovno
hovno

Reputation: 31

This is my solution:

                function getDataLine(grida, rowid){  //vykradeno z inineeditu a vohackovano

                    if(grida.lastIndexOf("#", 0) === 0){
                        grida = $(grida);
                    }else{
                        grida = $("#"+grida);
                    }

                    var nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;

                    ind = grida.jqGrid("getInd",rowid,true);
                    if(ind === false) {return success;}
                    editable = $(ind).attr("editable");
                    if (editable==="1") {
                        var cm;
                        var colModel = grida.jqGrid("getGridParam","colModel") ;
                        $("td",ind).each(function(i) {
                            // cm = $('#mygrid').p.colModel[i];
                            cm = colModel[i];
                            nm = cm.name;
                            if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
                                switch (cm.edittype) {
                                    case "checkbox":
                                        var cbv = ["Yes","No"];
                                        if(cm.editoptions ) {
                                            cbv = cm.editoptions.value.split(":");
                                        }
                                        tmp[nm]=  $("input",this).is(":checked") ? cbv[0] : cbv[1]; 
                                        break;
                                    case 'text':
                                    case 'password':
                                    case 'textarea':
                                    case "button" :
                                        tmp[nm]=$("input, textarea",this).val();
                                        break;
                                    case 'select':
                                        if(!cm.editoptions.multiple) {
                                            tmp[nm] = $("select option:selected",this).val();
                                            tmp2[nm] = $("select option:selected", this).text();
                                        } else {
                                            var sel = $("select",this), selectedText = [];
                                            tmp[nm] = $(sel).val();
                                            if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
                                            $("select option:selected",this).each(
                                                function(i,selected){
                                                    selectedText[i] = $(selected).text();
                                                }
                                            );
                                            tmp2[nm] = selectedText.join(",");
                                        }
                                        if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
                                        break;
                                }
                            }
                        });
                    }
                    return tmp;
                }

Upvotes: 1

StuartQ
StuartQ

Reputation: 3809

I think that Aidan's answer is by far the best.

$('#yourgrid').jqGrid("editCell", 0, 0, false);

This commits any current edits, giving you access to the real value. I prefer it because:

  • You don't have to hard-code any cell references in.
    • It is particularly well suited to using getRowData() to get the entire grid, as it doesn't care which cell you've just been editing.
    • You're not trying to parse some markup generated by jqGrid which may change in future.
    • If the user is saving, then ending the edit session is likely the behaviour they would want anyway.

Upvotes: 0

Wojtek Kruszewski
Wojtek Kruszewski

Reputation: 14750

My workaround is to attach an object containing orignal values to each tr element in the grid. I've used afterAddRecord callback to get my hands on the values before jqGrid throws them away and jQuery's "data" method to store them in the work.

Example:

afterInsertRow: function( rowid, rowdata, rowelem ) {
  var tr = $("#"+rowid);
  $(tr).data("jqgrid.record_data", rowelem);
},

“rowelem” is the array of cell values from our JSON data feed or [jsonReader] (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#jsonreader_as_function)

Then at any point I can fetch those attributes using:

$(tr).data(“jqgrid.record_data”).

More at: http://wojciech.oxos.pl/post/9423083837/fetching-original-record-values-in-jqgrid

Upvotes: 0

MoniR
MoniR

Reputation: 1391

you can use this directly....

onCellSelect: function(rowid,iCol,cellcontent,e) {
            alert(cellcontent);
        }

Upvotes: 1

Aidan
Aidan

Reputation: 69

After many hours grief I found this to be the simplest solution. Call this before fetching the row data:

$('#yourgrid').jqGrid("editCell", 0, 0, false);

It will save any current edit and will not throw if there are no rows in the grid.

Upvotes: 7

Cacho Santa
Cacho Santa

Reputation: 6924

In order to get the cell value when in-line editing you need to capture this event(or another similar event, check documentation):

beforeSaveCell: function (rowid, celname, value, iRow, iCol) { }

In the value parameter you have the 'value' of the cell that was currently edited.

To get the the rest of the values in the row use getRowData()

I lost a lot of time with this, hope this helps.

Upvotes: 0

jackysee
jackysee

Reputation: 2061

I've got a rather indirect way. Your data should have an unique id.

First, setting a formatter

$.extend(true, $.fn.fmatter, {          
numdata: function(cellvalue, options, rowdata){
    return '<span class="numData" data-num="'+rowdata.num+'">'+rowdata.num+'</span>';
}
});

Use this formatter in ColModel. To retrieve ID (e.g. selected row)

var grid = $("#grid"), 
    rowId = grid.getGridPara('selrow'),
    num = grid.find("#"+rowId+" span.numData").attr("data-num");

(or you can directly use .data() for latest jquery 1.4.4)

Upvotes: 0

David C
David C

Reputation: 21

Basically, you have to save the row before you access the cell contents.

If you do, then you get the value for the cell instead of the markup that comes when the cell is in edit mode.

jQuery.each(selectedRows, function(index, foodId) {
            // save the row on the grid in 'client array', I.E. without a server post
            $("#favoritesTable").saveRow(foodId, false, 'clientArray'); 

            // longhand, get grid row based on the id
            var gridRow = $("#favoritesTable").getRowData(foodId);

            // reference the value from the editable cell
            foodData += foodId + ":" + gridRow['ServingsConsumed'] + ',';
        });

Upvotes: 2

bigrockshow
bigrockshow

Reputation: 116

I think a better solution than using getCell which as you know returns some html when in edit mode is to use jquery to access the fields directly. The problem with trying to parse like you are doing is that it will only work for input fields (not things like select), and it won't work if you have done some customizations to the input fields. The following will work with inputs and select elements and is only one line of code.

ondblClickRow: function(rowid) {
    var val = $('#' + rowid + '_MyCol').val();
}

Upvotes: 0

David
David

Reputation: 42247

I think an extension of this would get it for you. retrieving-original-row-data-from-jqgrid

Upvotes: 0

Sergey
Sergey

Reputation: 3213

try subscribing to afterEditCell event it will receive (rowid, cellname, value, iRow, iCol) where value is your a new value of your cell

Upvotes: -1

raouf
raouf

Reputation: 585

Here is an example of basic solution with a user function.

    ondblClickRow: function(rowid) {
        var cont = $('#grid').getCell(rowid, 'MyCol');
        var val = getCellValue(cont);
    }

...

function getCellValue(content) {
    var k1 = content.indexOf(' value=', 0);
    var k2 = content.indexOf(' name=', k1);
    var val = '';
    if (k1 > 0) {
        val = content.substr(k1 + 7, k2 - k1 - 6);
    }
    return val;
}

Upvotes: 15

Justin Ethier
Justin Ethier

Reputation: 134275

As you stated, according to the jqGrid documentation for getCell and getRowData:

Do not use this method when you editing the row or cell. This will return the cell content and not the actual value of the input element

Since neither of these methods will return your data directly, you would have to use them to return the cell content itself and then parse it, perhaps using jQuery. It would be nice if a future version of jqGrid could provide a means to do some of this parsing itself, and/or provide an API to make it more straightforward. But on the other hand is this really a use case that comes up that often?

Alternatively, if you can explain your original problem in more detail there may be other options.

Upvotes: 4

tvanfosson
tvanfosson

Reputation: 532765

You can use getCol to get the column values as an array then index into it by the row you are interested in.

var col = $('#grid').jqGrid('getCol', 'Sales', false);

var val = col[row];

Upvotes: -2

Related Questions