How to get select's value in jqGrid when using <select> editoptions on a column - select

I have a couple of columns in jqGrid with edittype="select". How can I read the option value of the value currently selected in a particular row?
e.g.: When I provide the following option, how do I get "FE" for FedEx, etc.
editoption: { value: “FE:FedEx; IN:InTime; TN:TNT” }
getRowData() for the rowId/cellname returns only the text/displayed component of the select.
If I set a "change" data event on the column, the underlying fires change events only on mouse clicks, and not keyboard selects (there's numerous references to generic selects and mouse/keyboard issues).
Bottomline, when a new value is selected, I need to know the option value at the time of the change, and also prior to posting to the server.

You have to set the formatter of the column to 'select'
Example from the wiki:
colModel : [ {name:'myname',
edittype:'select', formatter:'select',
editoptions:{value:"1:One;2:Two"}} ...
]
See more here jqgridwiki
I was having the same problem and this worked like a charm

I just solved this question by using setting JqGrid unformat option and use the following function for unformatting cell value.
function Unformat_Select(cellvalue, options, cellobject)
{
var unformatValue = '';
$.each(options.colModel.editoptions.value, function (k, value)
{
if (cellvalue == value)
{
unformatValue = k;
}
});
return unformatValue;
}
The above method will be called everytime when grid need cell data like when you call "getRowData" method. However, my function only support key-paired value edit option. You need to change your data like the following pattern.
editoption:
{
value:
{
FE:'FedEx',
IN:'InTime',
TN:'TNT'
}
}
For more information about unformat option, you can see at the following link.
JqGrid Wiki - Custom Formatter
PS. It's possible to modify my function to support client-side dropdownlist value. But I think it's impossible to apply this function for server-side dropdownlist value.
Update
In the latest jqGrid 3.8.1, I just found some bug when user cancel editing row(or programmatically call "restoreRow" method), jqGrid will create label by using key of data (instead of value of data). I create the following function to fix this issue. For use this, you must it as custom formatter function of this column. This function maps cell value to value of list by comparing key or value.
function JqGridInlineEditor_SelectFormatter(cellvalue, options, rowObject)
{
var temp = '';
$.each(options.colModel.editoptions.value, function (key, value)
{
if (cellvalue == key || cellvalue == value)
{
temp = value;
return false;
}
});
return temp;
}
So, you can send key or value as column data to be rendered by the above custom formatter.

If in case you have requirement where each row has dropdown and it has values like
FE:'FedEx',
IN:'InTime',
TN:'TNT'
Now instead of saving the data to backend on dropdown change event;you want to save data on "Save" button click at row level but want to save dropdwon selected value (TN) not display text(TNT). You can create another hidden field to set selected country code on inline editing of dropdown. Here when user exit after cell inline editing afterSaveCell method will be called and you can set it as mentioned in below code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>http://stackoverflow.com/q/9655426/315935</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/jquery-ui.css" />
<link rel="stylesheet" type="text/css" href="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.3.1/css/ui.jqgrid.css" />
<style type="text/css">
html, body { font-size: 75%; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.3.1/js/i18n/grid.locale-en.js"></script>
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery.jqGrid-4.3.1/js/jquery.jqGrid.src.js"></script>
<script type="text/javascript">
//<![CDATA[
/*global $ */
/*jslint devel: true, browser: true, plusplus: true, nomen: true, unparam: true */
$(document).ready(function () {
'use strict';
var listOptions = "CN:Canada; US:United States; FR:France; IN:India";
var mydata = [{
name: "Toronto",
country: "CN",
continent: "North America",
countrycode: "CN"
}, {
name: "New York City",
country: "US",
continent: "North America",
countrycode: "US"
}, {
name: "Silicon Valley",
country: "US",
continent: "North America",
countrycode: "US"
}, {
name: "Paris",
country: "FR",
continent: "Europe",
countrycode: "FR"
}, {
name: "Pune",
country: "IN",
continent: "Asia",
countrycode: "IN"
}]
$("#gvManageMapping").jqGrid({
data: mydata,
datatype: "local",
colNames: ["Name", "Country", "Continent", "countrycode"],
colModel: [{
name: 'name',
index: 'name',
editable: false,
},
{
name: 'country',
index: 'country',
editable: true, edittype: "select", formatter: 'select', editoptions: {
value: listOptions,
}, editrules: { required: true, integer: false }, formatter: "select"
},
{
name: 'continent',
index: 'continent',
editable: false,
},
{
name: 'countrycode',
index: 'countrycode',
editable: false
}],
afterSaveCell: function (rowid, cellname, value) {
var selectedCountryCode, $this;
if (cellname === 'country') {
$this = $(this);
selectedCountryCode = $this.jqGrid("getCell", rowid, 'country');
$this.jqGrid("setCell", rowid, 'countrycode', selectedCountryCode);
}
},
pager: '#pager',
'cellEdit': true,
'cellsubmit': 'clientArray',
editurl: 'clientArray'
});
});
//]]>
</script>
</head>
<body>
<table id="gvManageMapping"><tr><td /></tr></table>
<div id="pager"></div>
</body>
</html>

The documentation for getRowData states:
Do not use this method when you editing the row or cell. This will return the cell content and not the actuall value of the input element
Is the row still being edited when you call getRowData()?
Update
Agreed, jqGrid does not handle <select> very well. In my application I actually was able to get around this by not specifying an edit option (meaning, key/value were both "FedEx"); the translation to ID is then done on the server. This is not the right way to code this, but it worked well enough for my needs at the time.

Related

Bootstrap-vue: Auto-select first hardcoded <option> in <b-form-select>

I'm using b-form-select with server-side generated option tags:
<b-form-select :state="errors.has('type') ? false : null"
v-model="type"
v-validate="'required'"
name="type"
plain>
<option value="note" >Note</option>
<option value="reminder" >Reminder</option>
</b-form-select>
When no data is set for this field I want to auto-select the first option in the list.
Is this possible? I have not found how to access the component's options from within my Vue instance.
your v-model should have the value of the first option.
example
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: 'a',
options: [
{ value: null, text: 'Please select an option' },
{ value: 'a', text: 'This is First option' },
{ value: 'b', text: 'Selected Option' },
{ value: { C: '3PO' }, text: 'This is an option with object value' },
{ value: 'd', text: 'This one is disabled', disabled: true }
]
}
}
}
</script>
You can trigger this.selected=${firstOptionValue} when no data is set.
what if we don't know what the first option is. The list is generated?
if you have dynamic data, something like this will work.
<template>
<div>
<b-form-select v-model="selected" :options="options" />
<div class="mt-3">Selected: <strong>{{ selected }}</strong></div>
</div>
</template>
<script>
export default {
data() {
return {
selected: [],
options: [],
};
},
mounted: function() {
this.getOptions();
},
methods: {
getOptions() {
//Your logic goes here for data fetch from API
const options = res.data;
this.options = res.data;
this.selected = options[0].fieldName; // Assigns first index of Options to model
return options;
},
},
};
</script>
If your options are stored in a property which is loaded dynamically:
computed property
async computed (using AsyncComputed plugin)
through props, which may change
Then you can #Watch the property to set the first option.
That way the behavior of selecting the first item is separated from data-loading and your code is more understandable.
Example using Typescript and #AsyncComputed
export default class PersonComponent extends Vue {
selectedPersonId: string = undefined;
// ...
// Example method that loads persons data from API
#AsyncComputed()
async persons(): Promise<Person[]> {
return await apiClient.persons.getAll();
}
// Computed property that transforms api data to option list
get personSelectOptions() {
const persons = this.persons as Person[];
return persons.map((person) => ({
text: person.name,
value: person.id
}));
}
// Select the first person in the options list whenever the options change
#Watch('personSelectOptions')
automaticallySelectFirstPerson(persons: {value: string}[]) {
this.selectedPersonId = persons[0].value;
}
}

How can I render a form with form.io using vanilla JS?

I am playing with the form.io demo on CodePen, but it uses Angular. Assuming I have a basic JSON form and an html page not tied to any framework, what is the simplest way to render the form, initializing the form with an optional model, and collecting the model once the form is submitted?
Is there a form.io JavaScript library that does such a thing?
Example form.io JSON form snippet:
{
components: [
{
input: true,
tableView: true,
inputType: "text",
inputMask: "",
label: "First Name",
key: "firstName",
The formio developers provide formio.js for this specific use case. Here is the link
as per their own documentation:
in your index:
<link rel="stylesheet" href="./node_modules/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="./node_modules/formiojs/dist/formio.form.min.css" />
<script src="node_modules/formiojs/dist/formio.form.min.js"></script>
<div id="formID" class="demo-box">Loading...</div>
then in your js:
let schema = {
components: [
{
input: true,
tableView: true,
inputType: "text",
inputMask: "",
label: "First Name",
key: "firstName"
}]
}
let data = {}
let formio = new Formio.createForm(document.getElementById('formID'), schema, data)
i recommend using this site to build your schema: https://formio.github.io/formio.js/app/sandbox

Bind results of client side calculations to control (e.g. chart)

If the source for my chart in SAP UI5 is not a model loaded from a server or file, but the result of some calculations (groupings/maths) based on an existing model, how do I correctly bind it to the chart control and use the data?
You first create the outcome of the calculation. Then you transfer it in a new JSON model and use the setData function to pass the results.
Then you bind the control to the new JSON model. I try to make up some dummy code probably located in your controller:
var data = modelWithRawData.getData();
calculationOutput = doComplicatedCalculation(data);
var calculationModel = new sap.ui.model.json.JSONModel(calculationOutput)
myView.setModel(calculationModel, "calculationModel");
And in the path of your bindings you now need to reference the modelName. Eg in an xmlView:
<Chart data="{calculationModel>/PathToRelevantData}">
<!-- more xml -->
Here's a working example using the sap.viz library:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />
<script src="resources/sap-ui-core.js" id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons,sap.ui.layout,sap.ui.ux3,sap.ui.table,sap.m,sap.viz"
data-sap-ui-theme="sap_goldreflection">
</script>
<script>
var oModel = new sap.ui.model.json.JSONModel({
businessData : [
{text: "A", value: 100},
{text: "B", value: 200},
{text: "C", value: 300}
]
});
//DO SOME ADVANCE CALCULATION WITH THE JSON DATA...
var data = oModel.getData();
data.businessData[0].value += 30;
data.businessData[1].value = data.businessData[1].value * 2;
data.businessData[2].value = data.businessData[2].value - 100;
//END OF SOME ADVANCE CALCULATION WITH THE JSON DATA...
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions : [{axis : 1, name : 'Text', value : "{text}"}],
measures : [{name : 'Value', value : '{value}'},
],
data : {path : "/businessData"}
});
var oBarChart = new sap.viz.ui5.Bar({
title : {
visible : true,
text : 'My bar chart'
},
dataset : oDataset
});
// attach the model to the chart and display it
oBarChart.setModel(oModel);
oBarChart.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
Hope this helps.

jsTree - cannot create new node - all other functions work well

Deselect and hover funcntions work fina but create/delete/rename don't.
What do is do wrong?
info.json contains 5 nodes marked from 1 to 5.
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="jstree\dist\themes\default\style.min.css" />
<script src="jstree\dist\jstree.js"></script>
<script>
$(function() {
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
}
}
}
});
});
</script>
</head>
<body>
<div id="container" >
<div id="nav_bar">
<button id="create" onclick = "demo_create()">Create</button>
</div>
<div id="test_tree"></div
</div>
<script>
function demo_create() {
$.jstree.reference('#test_tree').hover_node('ajson5');
$.jstree.reference('#test_tree').deselect_node('ajson1');
$.jstree.reference('#test_tree').create_node();
};
</script>
</body>
I used same example from official site but it doesn't work
Thanks for any help.
First, in order for changes to be made to the tree, checkcallback in core config need to be set to true.
$('#test_tree').jstree({
'core' : {
'data' : {
'url' : 'info.json',
'data' : function (node) {
return { 'id' : node.id };
},
check_callback : true
}
}
You need to at least pass the parent.id to the create_node function.
$.jstree.reference('#test_tree').create_node('ajson1');
You could check the API at the jstree website for the full parameter list.
Demo jsTreeView 3.2.1 version
$("#treeView").jstree({ 'core': {
'check_callback': true,
'themes': {
"variant": "large"
},
'data':
[{"id":"1","parent":"#","text":"Parent Node"}]
}
});
You are missing the single quotation mark for the check_callback, after using that it will work. e.g. 'check_callback': true.
Code to create new Node
var ref_treeview = $("#treeView").jstree(true);
sel = ref_treeview.get_selected();
if (!sel.length) {
return false;
}
sel = sel[0];
sel = ref_treeview.create_node(sel, "childNode", "last", CreateNode,true);
Here CreateNode is my Callback function name
you have to send the selected element.
use the following (this is basically the code of the create button in the demo page http://www.jstree.com/demo/):
var tree = $("#test_tree").jstree(true);
var sel = tree.get_selected();
if (!sel.length)
{
return false;
}
sel = sel[0];
sel = tree.create_node(sel);
if (sel)
{
tree.edit(sel);
}
At the time when you create the jstree instance you just need to configure the
'core' setting as shown bellow:
$(function () {
$('#jstree').jstree({
'core':{check_callback : true}
});
You have to set the type of the newly created node like so:
$('#tree').jstree().create_node('#', {'id': 'blah', 'text': 'new node', 'type': 'folder'}, 'last', function() {
console.log('done');
});
jstree documentation should be improved.
using code from the other answers, I was able to make the following work:
Please note, this actually works. I am using it to create menus for an external ajax API.
function makeNode(menunode, menuname){
var inst = $.jstree.reference("#treemenu"); //get menu instance
var obj = inst.get_node(menunode);
inst.create_node(obj, menuname); //creates nodes. use "#" to make root nodes
inst.open_node(obj); // open the node (unfold)
});
usage:
//create menu instance and allow tree changes
$('#treemenu').jstree({'core' : {'check_callback': true}});
makeNode("#", "main menu"); //makes root node
makeNode("#j1_1", "submenu in main menu"); //makes sub node
this is assuming that you have a div with id="treemenu" thusly
<div id="treemenu"></div>

Drop Down in JQGrid

I am new to JQgrid and we are using Perl Catalyst to build the application.
I need to have a drop down for the Operating system field
Please find the code for JQgrid
<title>Server Details </title>
<link rel="stylesheet" type="text/css" media="screen" href="[% c.uri_for('/static/css/cupertino/jquery-ui-1.10.3.custom.css') %]" />
<link rel="stylesheet" type="text/css" media="screen" href="[% c.uri_for('/static/plugins/jqGrid/css/ui.jqgrid.css') %]" />
<link rel="stylesheet" type="text/css" media="screen" href="[% c.uri_for('/static/plugins/jqGrid/css/print-container.css') %]" />
<script src="[% c.uri_for('/static/plugins/jqGrid/js/i18n/grid.locale-en.js')%]" type="text/javascript"></script>
<script src="[% c.uri_for('/static/plugins/jqGrid/js/jquery.printElement.js')%]" type="text/javascript"></script>
<script src="[% c.uri_for('/static/plugins/jqGrid/js/printing.js')%]" type="text/javascript"></script>
<script src="[% c.uri_for('/static/plugins/jqGrid/js/export_to_excel.js')%]" type="text/javascript"></script>
<script src="[% c.uri_for('/static/plugins/jqGrid/js/jquery.jqGrid.src.js') %]" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#list").jqGrid({
url:"[% c.uri_for("server_details_json") %]",
datatype:'json',
mtype:'GET',
colNames:['Server Id' , 'Host Name', 'IP Address','Operating System','Operating System Version', 'Network Domain','Business Unit'],
colModel:[
{name:'server_id', index:'server_id', align:'centre',editable:false},
{name:'server_name', index:'server_name', align:'left',editable:true},
{name:'ip_address', index:'ip_address', align:'left',editable:true},
{name:'operating_system', index:'operating_system', align:'left',editable:true, edittype: 'select',
searchoptions: {value:getOptionsList(),
sopt:['eq']}},
{name:'operating_system_version', index:'operating_system_version', align:'left',editable:true},
{name:'domain', index:'domain', align:'left',editable:true},
{name:'business_unit', index:'business_unit', align:'left',editable:true},
],
pager:'#pager',
rowNum:10,
autowidth:true,
autoheight:true,
rowList:[10,20,30,1000000000000000000],
loadComplete: function() {
$("option[value=1000000000000000000]").text('All');
},
sortname:'server_id',
sortorder:'asec',
shrinkToFit:true,
viewrecords:true,
gridview:true,
height:'auto',
editurl:"[% c.uri_for("postrow") %]",
caption:'Server List '
});
$("#list").jqGrid('navGrid', '#pager',{
view:false,
del:true,
add:true,
edit:true,
search: true,
refresh: true,
print:true
},
{height:250,width:500,reloadAfterSubmit:true}, // edit options
{height:480,reloadAfterSubmit:false}, // add options
{reloadAfterSubmit:false}, // del options
{} // search options
)
// setup grid print capability. Add print button to navigation bar and bind to click.
setPrintGrid('list','pager','Server Details');
setExcelGrid('list','pager','/tams/Server_Details_CSV','Server Details1');
});
</script>
<script>
function getOptionsList(){
$.ajax({
type: "POST",
url:"[% c.uri_for("OS_json") %]",
async:false,
dataType: 'json',
success: function(data){
options=data.value;
},
failure :function(xhr,status,msg) {
alert("Unexpected error occured. !!!"+msg);
}
});
return options;
}
</script>
<body>
<table id="list"><tr><td/></tr></table>
<div id="pager"></div>
</body>`
The Json Data is like this
[{"value":"Windows","id":"86"},{"value":"AIX","id":"87"}]
Can some one help me Thanks in advance for your precious time
First of all you defined searchoptions.value for operating_system column which will be used during searching and not during editing. Moreover the property will work in Searching dialog only if you would add additional property stype: "select". So you should add editoptions: {value: getOptionsList() } to have <select> during editing.
The format of value for editoptions.value and searchoptions.value can be either the string like
"86:Windows;87:AIX"
or an object like
{"86": "Windows", "87": "AIX"}
and not [{"value":"Windows","id":"86"},{"value":"AIX","id":"87"}] which you currently use.
You should change the code of getOptionsList to construct the corresponding results. By the way I prefer to use String form instead of Object form because it allows to specify the exact order of <option> elements in the <select>. The order of options in case of usage object form can be different in different web browsers.
I would recommend you to change your code so that you don't use synchronous Ajax request. Instead of that you can use editoptions {dataUrl: "[% c.uri_for("OS_json") %]", buildSelect: function (data) {...}}. You should additionally define ajaxSelectOptions: {dataType: "json"}. The callback function buildSelect get the server response (data) and it should return the HTML fragment of <select> with all <option> elements. You can find some examples here, here and here.
UPDATED: The code of buildSelect can be something like
buildSelect: function (data) {
var html = "<select>", length = data.length, i, item;
for (i = 0; i < length; i++) {
item = data[i];
html += '<option value=' + item.id + '>' + item.value + '</option>';
}
return html + "/<select>";
}
if you want that results of editing of the select will be sent as select id (like 86 for "Windows") to the server (see the demo). If you want that server get the name (like "Windows") then you need fill value of <option> elements using value property and ignore the id value:
buildSelect: function (data) {
var html = "<select>", length = data.length, i, item;
for (i = 0; i < length; i++) {
item = data[i];
html += '<option value=' + item.value + '>' + item.value + '</option>';
}
return html + "/<select>";
}
see the demo. You can use Fiddler, Developer Tools of IE or other free tools to trace the exact HTTP traffic during editing.
Your colModel must be like,
{ name: 'Decision', width: 200, editable: true, formatter: 'select', edittype: 'select',
editoptions: {
value: {
'1': 'Option 1',
'2': 'Option 2',
'3': 'Option 3'
}
}
},
I guess, it must be editoptions instead of searchoptions.
Here is an example grid, thanks to Oleg