set an id at "Raphaeljs set" - set

i want to set an id to Raphael set because i want to display it after an event click.
this is my set:
var divResult = document.getElementById('printResult');
var space2Draw = Raphael(divResult, 1600, 900);
var st = space2Draw.set();
st.push(
space2Draw.circle(newXCoordinates, newYCoordinates, 20).click((function (valore) {
return function () {
window.open("index-point.html?id=" + (valore) + "&type=" + type + "&description=" + description + "&name=" + name);
}
}(valore))).mouseover(function () {
this.attr({ 'cursor': 'pointer' });
this.attr({ 'opacity': '.50' });
}).mouseout(function () {
this.attr({ 'opacity': '1' });
})
);
in my page i have a button:
function show(){
var element = space2Draw.getById(-1);
element.show();
}
}
Is not possible to set an id in this way : set.id = -1?
How can I set an id and then I find the set?
Thanks in advance for the help.

You can try using setAttribute() to add a CLASS for the elements you want to access later, and then modify their CSS propperties. The first step would be to change the CLASS of each element:
myElement.node.setAttribute("class", "class_name");
Unfortunately, Raphael does not allow you to handle sets as unique HTML objects, so you cannot do this for the entire set at once. Instead, you might have to do this for each element in your set, possibly with a for cycle, something like this:
for (var i=0; i<st.length; i++) {
st[i].node.setAttribute("class", "class_name");
}
Then, using JQuery, you can modify the CSS properties of the CLASS you created in order to display the elements in your set.
function show(){
$('.class_name').css('display', 'block');
}
I hope this helps.

Maybe you can use Raphael data() function to assign any data to your element/set.
Example:
// you can keep global var for your id and increment it within your code
var id = 0;
var p = Raphael(100, 100, 500, 500),
r = p.rect(150, 150, 80, 40, 5).attr({fill: 'red'}),
c = p.circle(200, 200, 70).attr({fill: 'blue'});
var set = p.set(r,c).data("id", id);
id++;
// then in your click event to get the id you can do
var whichSet = this.data("id");
// data("id") will return you the global id variable
Good Luck

Related

ckeditor balloonpanel not staying attached to an element when scrolling

UPDATE balloon panels are staying attached in below code. We still have an issue where when we close a balloon panel, and then scroll afterward, the balloon panel that was just closed reappears. Here’s the updated code.
HERE WAS THE ORIGINAL QUESTION I am trying to get the ckeditor balloonpanel to stay attached to the element it was initially attached to; currently, when I scroll in the editor, the balloonpanels do not stay in place. The problem is that the balloonpanels shift when the user scrolls in the editor -- they do not remain attached to their initial element they were attached to when I scroll in the editor. Here is the code for the ckeditor plugin. It creates a balloonpanel in a for loop on return of an web service Ajax call and stores the panel in a global array called panels :
( function() {
var arr = new Array();
var panels = [];
var saveCmd = {
readOnly: 1,
modes: { wysiwyg: 1,source: 1 },
exec: function( editor ) {
if ( editor.fire( 'grade_level_score' ) ) {
var $form = editor.element.$.form;
/**
* Destroys the balloon panel by removing it from DOM and purging
* all associated event listeners.
*/
// https://github.com/ckeditor/ckeditor-dev/blob/64749bb245d1e91f6a4ac4e97c9648ec47acda91/plugins/balloonpanel/plugin.js#L743-L745
var panel;
while ( ( panel = panels.pop() ) ) {
panel.destroy();
}
arr = []; // clear the array of user-editable areas
panels = []; // clear the array of panels
// https://stackoverflow.com/a/48022658
var ele = $(editor.editable().$);
var elementOfClass;
var i = 1;
// class "ice-ice-editable" is in a span
$('span',ele).each(function(){
// https://stackoverflow.com/a/35866999
var iceIceEditableClass = "ice-ice-editable";
var hasClassIceIceEditable = $(this).hasClass(iceIceEditableClass);
if( hasClassIceIceEditable ) {
console.log($(this).text());
console.log($(this).attr('class'));
console.log($(this).attr('id'));
var userEditable = "user-editable-" + i;
// If the specified attribute already exists, only the value is set/changed.
this.setAttribute("id","user-editable-" + i);
var record1 = { id : userEditable , userEditableArea : $(this).text() };
arr.push(record1);
i++;
}
});
var gradeLevelObject = new Object();
gradeLevelObject.textAreas = arr;
// var responseGradeLevelScoreWS = gradeLevelScore(gradeLevelObject);
// BEGIN for testing
var result = '{"textAreas":[{"id":"user-editable-1","userEditableArea":"[Insert information specific to what is being addressed (a brief description of request(s) and/or concern(s). Specific training resource document for letter writing assistance will be referenced here.] ","score":22.24,"readingGrade":7,"issues":["asdf","zxcv"]},{"id":"user-editable-2","userEditableArea":"[Insert information specific to what is being addressed (a brief description of request(s) and/or concern(s). Specific training resource document for letter writing assistance will be referenced here.] ","score":22.24,"readingGrade":0,"issues":[]},{"id":"user-editable-3","userEditableArea":"[Insert information specific to what is being addressed (a brief description of request(s) and/or concern(s). Specific training resource document for letter writing assistance will be referenced here.] ","score":22.24,"readingGrade":0,"issues":[]},{"id":"user-editable-4","userEditableArea":"[Insert information specific to what is being addressed (a brief description of request(s) and/or concern(s). Specific training resource document for letter writing assistance will be referenced here.] ","score":22.24,"readingGrade":0,"issues":[]}]}';
var responseGradeLevelScoreWS = JSON.parse(result);
// END for testing
console.log(responseGradeLevelScoreWS);
var i;
for (i = 0; i < responseGradeLevelScoreWS.textAreas.length; i++){
if ( responseGradeLevelScoreWS.textAreas[i].readingGrade > 6 ) {
var j;
var issues = '';
for (j = 0; j < responseGradeLevelScoreWS.textAreas[i].issues.length; j++) {
issues += '<p>' + responseGradeLevelScoreWS.textAreas[i].issues[j] + '</p>';
}
panel = new CKEDITOR.ui.balloonPanel( editor, {
title: 'Grade: ' + responseGradeLevelScoreWS.textAreas[i].readingGrade + '. Score: ' + responseGradeLevelScoreWS.textAreas[i].score,
content: ( (typeof issues === 'undefined' || issues == null) ? 'There are no suggestions in order to descrease the grade level score' : issues ),
width: 500,
height: 120
});
var element = editor.document.getById(responseGradeLevelScoreWS.textAreas[i].id);
panel.attach( element );
panel.registerFocusable(element);
panels.push( panel );
issues = '';
}
}
// We'll use throttling for scroll listener to reduce performance impact.
var scrollListener = CKEDITOR.tools.eventsBuffer( 100, function() {
for (i = 0; i < panels.length; i++) {
panels[i].attach( editor.document.getById( responseGradeLevelScoreWS.textAreas[i].id ), {
focusElement: false,
show: false
} );
}
} );
editor.window.on( 'scroll', scrollListener.input );
if ( $form ) {
try {
//$form.submit();
} catch ( e ) {
// If there's a button named "submit" then the form.submit
// function is masked and can't be called in IE/FF, so we
// call the click() method of that button.
if ( $form.submit.click )
$form.submit.click();
}
}
}
}
};
var pluginName = 'grade_level_score';
// Register a plugin named "save".
CKEDITOR.plugins.add( pluginName, {
// jscs:disable maximumLineLength
lang: 'en,en-au,en-ca,en-gb,es,es-mx', // %REMOVE_LINE_CORE%
// jscs:enable maximumLineLength
icons: 'grade_level_score', // %REMOVE_LINE_CORE%
hidpi: true, // %REMOVE_LINE_CORE%
init: function( editor ) {
// Save plugin is for replace mode only.
if ( editor.elementMode != CKEDITOR.ELEMENT_MODE_REPLACE )
return;
var command = editor.addCommand( pluginName, saveCmd );
command.startDisabled = !( editor.element.$.form );
editor.ui.addButton && editor.ui.addButton( 'Grade_Level_Score', {
//label: editor.lang.save.toolbar,
label: "Grade Level Score",
command: pluginName,
toolbar: 'custom,100'
} );
}
} );
} )();
Only Balloon Toolbar has built-in functionality for automatic reposition on scroll. Balloon Panel itself is a static element. However, it can be easily achieved by attaching scroll listener and repositioning visible panels on scroll:
// We'll use throttling for scroll listener to reduce performance impact.
var scrollListener = CKEDITOR.tools.eventsBuffer( 100, function() {
for (i = 0; i < panels.length; i++) {
panels[i].attach( editor.document.getById(ids[i]), {
focusElement: false,
show: false
} );
}
} );
editor.window.on( 'scroll', scrollListener.input );
See this codepen for the full code (reusing some parts of your original code).

Leaflet Icon on multiple layer calling with ajax

i've a little issue for calling new icon with leaflet.
this is my code and i'm using the ajax lib leaflet-ajax.
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
var Icon1 = L.icon({
iconUrl: '/img/pin.svg',
iconSize: [38, 40]
});
var Icon2 = L.icon({
iconUrl: '/img/pin2.svg',
iconSize: [38, 40]
});
var Icon3 = L.icon({
iconUrl: '/img/pin3.svg',
iconSize: [38, 40]
});
function popUp(feature, layer) {layer.bindPopup('<p><b>' + feature.properties.name + '</b></p>' + '<p>' + feature.properties.description + '</p>');}
function popUp2(feature, layer) {layer.bindPopup('<p><b>' + feature.properties.name + '</b></p>' + '<p>' + feature.properties.special + '</p>');}
and where i think i have my issue with the call method for the icon
// call json
var geojsonLayer1 = new L.GeoJSON.AJAX("/json/jsonlayer1.json", {onEachFeature:popUp}, {icon:Icon1});
var geojsonLayer2 = new L.GeoJSON.AJAX("/json/jsonlayer2.json", {onEachFeature:popUp}, {icon:Icon2});
var geojsonLayer3 = new L.GeoJSON.AJAX("/json/jsonlayer3.json", {onEachFeature:popUp2}, {icon:Icon3});
// create group layer
var group1 = L.layerGroup([geojsonLayer1]);
var group2 = L.layerGroup([geojsonLayer2]);
var group3 = L.layerGroup([geojsonLayer3]);
// call group layer on dialog box
var checkboxesJson = {
"layer1": group1,
"layer2": group2,
"layer3": group3
};
L.control.layers(null,checkboxesJson).addTo(map);
Thank you for your help !
If my understanding is correct, you are trying to create a customized GeoJSON layer group through using leaflet-ajax plugin. But you do not know how to specify the icon that should be applied on markers for points of your GeoJSON data?
It looks like this plugin will simply use all standard L.GeoJSON options that are specified in the second argument of the constructor / factory, as you did for your onEachFeature option. Note that you can have many options in one single object.
However, you should use option pointToLayer instead of just icon, which is an option for a Marker. The function that you pass to pointToLayer should return an L.Marker, where indeed you would use the icon option.
For example you could do:
var geojsonLayer1 = L.geoJson.ajax(
"/json/jsonlayer1.json",
{
onEachFeature: popUp,
pointToLayer: function (feature, latlng) {
return L.marker(latlng, { icon: Icon1 })
}
});
Note that it is usually recommended to instantiate one icon per marker, even though it should work in your simple case.
By the way, note that L.geoJson (and with ajax plugin, L.geoJson.ajax) return an extended type of L.LayerGroup, so you do not have to import them into a new Layer Group to be able to use them in the Layers Control.
Therefore you could directly do:
// call group layer on dialog box
var checkboxesJson = {
"layer1": geojsonLayer1,
"layer2": geojsonLayer2,
"layer3": geojsonLayer3
};
L.control.layers(null,checkboxesJson).addTo(map);

Famo.us - triggering event and piping

Let's say I have three Views. AppView, MenuView and StripView. MenuView contains multiple StripViews and AppView contains one MenuView. How can I trigger event from StripView and listen on that event on AppView.
EDIT
Let's say I want to click on ImageSurface on StripView and reigster that event on AppView, and then do some transitionig.
MY SOLUTION
Everything is based on Timbre app, created in Famou.us Starter Kit Reference Tutorials
// StripView.js (_setListeners() is called in StripView constructor and bodySurface is defined in code)
function _setListeners() {
var eventScope = this._eventOutput;
this.backgroundSurface.on('click',function(){
eventScope.emit('test', { somedata:'some value'} );
}.bind(this));
}
// MenuView.js (_createStripViews() is called in MenuView constructor)
function _createStripViews() {
this.stripModifiers = [];
var yOffset = this.options.topOffset;
for (var i = 0; i < this.options.stripData.length; i++) {
var stripView = new StripView({
iconUrl: this.options.stripData[i].iconUrl,
title: this.options.stripData[i].title
});
var stripModifier = new StateModifier({
transform: Transform.translate(0, yOffset, 0)
});
this.stripModifiers.push(stripModifier);
this.add(stripModifier).add(stripView);
yOffset += this.options.stripOffset;
stripView.pipe(this._eventOutput);
}
}
//AppView.js (menuView is defined in code and _setListeners() is called in AppView constructor)
function _setListeners() {
this.menuView.on('test',function(){
console.log("IT WORKS");
}.bind(this));
}
You want to use Views built in handlers to achieve this. These are _eventInput and _eventOutput.. Here is an example using an ImageSurface in StripView and responding to a click in AppView..
Hope it helps!
// In StripView.js
var imageSurface = new ImageSurface();
imageSurface.on('click',function(){
this._eventOutput.trigger('image-click', { somedata:'some value'} );
}.bind(this));
// In AppView.js
var stripView = new StripView();
this.subscribe(stripView);
this._eventInput.on('image-click',function(data){
// Do Something
});

Magento Enterprise Tabs - How to select specific tab in link?

I am trying to link to a specific tab in Magento Enterprise. It seems that all of the answers I've found don't apply well to their method. I just need a link to the page to also pull up a specific tab. This is the code they use:
Enterprise.Tabs = Class.create();
Object.extend(Enterprise.Tabs.prototype, {
initialize: function (container) {
this.container = $(container);
this.container.addClassName('tab-list');
this.tabs = this.container.select('dt.tab');
this.activeTab = this.tabs.first();
this.tabs.first().addClassName('first');
this.tabs.last().addClassName('last');
this.onTabClick = this.handleTabClick.bindAsEventListener(this);
for (var i = 0, l = this.tabs.length; i < l; i ++) {
this.tabs[i].observe('click', this.onTabClick);
}
this.select();
},
handleTabClick: function (evt) {
this.activeTab = Event.findElement(evt, 'dt');
this.select();
},
select: function () {
for (var i = 0, l = this.tabs.length; i < l; i ++) {
if (this.tabs[i] == this.activeTab) {
this.tabs[i].addClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 2;
/*this.tabs[i].next('dd').show();*/
new Effect.Appear (this.tabs[i].next('dd'), { duration:0.5 });
this.tabs[i].parentNode.style.height=this.tabs[i].next('dd').getHeight() + 15 + 'px';
} else {
this.tabs[i].removeClassName('active');
this.tabs[i].style.zIndex = this.tabs.length + 1 - i;
this.tabs[i].next('dd').hide();
}
}
}
});
Anyone have an idea?
I would consider modifying how the class starts up.
initialize: function (container) {
this.container = $(container);
this.container.addClassName('tab-list');
this.tabs = this.container.select('dt.tab');
// change starts here //
var hashTab = $(window.location.hash.slice(1));
this.activeTab = ( this.tabs.include(hashTab) ? hashTab : this.tabs.first());
// change ends here //
this.tabs.first().addClassName('first');
this.tabs.last().addClassName('last');
this.onTabClick = this.handleTabClick.bindAsEventListener(this);
for (var i = 0, l = this.tabs.length; i < l; i ++) {
this.tabs[i].observe('click', this.onTabClick);
}
this.select();
}
Here, I have only changed how the initial tab is chosen. It checks for an URL fragment which is commonly known as a hash, if that identifies one of the tabs it is preselected. As a bonus the browser will also scroll to that element if possible.
Then you only need to append the tab's ID to the URL. For example you might generate the URL by;
$productUrl = Mage::getUrl('catalog/product/view', array(
'id' => $productId,
'_fragment' => 'tab_id',
));
If you've recently migrated from an earlier Magento release, e.g. from Enterprise 1.11 to Enterprise 1.12, make sure the javascript in /template/catalog/product/view.phtml
right after the foreach that generates the tabs gets updated to the 1.12 version:
<script type="text/javascript">
var collateralTabs = new Enterprise.Tabs('collateral-tabs');
Event.observe(window, 'load', function() {
collateralTabs.select();
});
</script>
surfimp's VERY helpful suggestions did not produce the desired opening of the closed tab otherwise. Once this updated javascript was added, clicking on a link to read Review or Add Your Review on the product page, jumped to the Reviews tab, even if the tab had been hidden.
Similar to Zifius' answer, you can modify the initialize function to just take another argument which will be the active tab.
Event.observe(window, 'load', function() {
new Enterprise.Tabs('collateral-tabs', $('tab_review'));
});
and then in the scripts.js (or wherever this class may exist for you)
initialize: function (container, el) {
...
this.activeTab = el;
...
}
Use whatever logic in the template you like to set 'el' to the desired value.
The reason I did it this way is because when I used Zifius' method, the desired tab would be the active tab, but the default tab's content was still displayed.
Had the same task yesterday and as I don't know about prototype much I solved it by adding another method:
selectTab: function (element) {
this.activeTab = element;
this.select();
},
Usage:
var Tabs = new Enterprise.Tabs('collateral-tabs');
Tabs.selectTab($('tabId'));
Would like to know if it's a correct approach

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).
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.
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;
}
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.
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.
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);
}
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'] + ',';
});
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');
you can use this directly....
onCellSelect: function(rowid,iCol,cellcontent,e) {
alert(cellcontent);
}
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;
}
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
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
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>The Value I'm After</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.
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);
I think an extension of this would get it for you.
retrieving-original-row-data-from-jqgrid
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();
}
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)
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.
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
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.
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');
I obtain edit value using javascript:
document.getElementById('idCell').value
I hope this info useful for someone.
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.
try subscribing to afterEditCell event it will receive (rowid, cellname, value, iRow, iCol) where value is your a new value of your cell
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];

Resources