Jqgrid + JQuery Autocomplete multiple input - jquery-ui

I have the grid set up and working nicely. I wanted to add multiple input autocomplete functionality to the form view in JqGrid. The multiple autocomplete works but the extractLast function seems not to be working and I can add duplicate inputs.
Heres the code:
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split( term ).pop();
}
function autocomplete_element(value, options) {
// creating input element
var $ac = $('<input type="text"/>');
// setting value to the one passed from jqGrid
$ac.val(value);
// creating autocomplete
$ac.autocomplete(
{source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
response( $.ui.autocomplete.filter(
availableTags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
// returning element back to jqGrid
return $ac;
}
function autocomplete_value(elem, op, value) {
if (op == "set") {
$(elem).val(value);
}
return $(elem).val();
}
Grid colmodel:
{
...
editable: true,
edittype: "custom",
editoptions: {
custom_element: autocomplete_element,
custom_value: autocomplete_value
}
},
Which I found from JQuery UI
and German Rumm's blog
Any suggestions?
UPDATED!

It looks like example on jQuery UI site allows selecting the same element multiple times as well. The problem is in source function - it always checks the last term against all available terms when creating a suggest list.
Modify select callback to display only those terms that are not already present in a field.
source: function(request, response) {
var terms = request.terms.split(/,\s*/);
var last_term = terms.pop();
var tags = $.grep(availableTags, function(el) {
return $.inArray(el, terms) == -1);
});
response($.ui.autocomplete.filter(tags, last_term))
}

Related

ui-grid rowTemplate: how to dynamically change row color based on column data

I have a server data embedded with values that determine the row-color.
var ngBody = angular.module ('BodySpace', [
'ui.grid', 'ngSanitize', 'ngResource'
, 'ui.grid.selection', 'ui.bootstrap'
, 'ui.grid.resizeColumns'
]);
ngBody.controller('ngController', function($scope, $http, $filter, uiGridConstants) {
angular.element(document).ready(function () {
initScope( $scope, uiGridConstants, $filter);
$scope.Get2Data();
} );
initScope( $scope, uiGridConstants, $filter);
$scope.Get2Data = function() {
$scope.uiGrid306.data = serverdata;
:
:
:
}
})
The requested data from the server has a column that controls the row color. What should I write in my row template to reference my data column that determines each row's color to render?
On initiating your ui-grid, you will apply a row-template in which you execute the code referencing your column data that decide the row-color - here in this example, it is _ab_x_style which stores the name of my style class.
function initGrid( $scope, uiGridConstants, $filter){
$scope.uiGrid306 = {
rowTemplate: 'rowTemp.html'
, columnDefs: [{
field: 'FIELD1', name: 'my field name', width: "7%"
, filter: { type: uiGridConstants.filter.SELECT, selectOptions: Opts }
}, { ...
}, { ...
}]
}
}
You place your rowTemp.html where your .html page is. In your rowTemp.html, you have
<div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.uid" ui-grid-one-bind-id-grid="rowRenderIndex + '-' + col.uid + '-cell' " class="ui-grid-cell" ng-class="row.entity._ab_x_style" role="{{col.isRowHeader ? 'rowheader' : 'gridcell' }}" ui-grid-cell></div>
plunker

overriding _rendermenu in jquery autocomplete throws js error

I tried to override _rendermenu in jquery autocomplete. The list is getting generated but every time I hover over the results i get the following js error
Uncaught TypeError: Cannot read property 'value' of undefined in jquery-ui.js
the code used is
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme",
"AA",
"BB",
"CC",
"DD",
"EE",
"FF",
"GG",
"HH",
"II",
"JJ",
"KK"
];
var atComplete=$( "#autoCompleteText" ).autocomplete({
delay:0,
source:availableTags,
autoFocus: true,
minLength: 0,
appendTo: "#result"
}).focus(function () {
$(this).autocomplete("search");
}).data('ui-autocomplete');
atComplete._renderMenu = function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItem( ul, item );
});
};
atComplete._renderItem = function(ul, item) {
console.log("item in render item:",item);
return $("<li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
};
});
If you look at the API docs for _renderMenu you'll see the reason you're getting an error:
Creation of the individual <li> elements should be delegated to _renderItemData(), which in turn delegates to the _renderItem() extension point.
You're using renderItem() directly. This means that you're not actually binding item data to the .data('ui-autocomplete-item') cache, which the widget attempts to read when drawing the menu -- but since it's undefined, the page is throwing an error.
To fix it all you need to do is change the call to _renderItem to call _renderItemData instead:
atComplete._renderMenu = function( ul, items ) {
var that = this;
$.each( items, function( index, item ) {
that._renderItemData( ul, item );
});
};

How to use port.on() and port.emit() with each other

I am trying to use a page-worker and a pageMod together using port.on() and port.emit(), but the signals from define.js do not have any effect on the pageMod's port.on()... Is this the proper way to use port.on() and port.emit() or is chaining the two together this way not allowed?
index.js:
pageMod.PageMod({
include: "*",
contentScriptWhen: "ready",
contentScriptFile: [
data.url("jquery.js"),
data.url("jquery-ui.min.js"),
data.url("define.js")
],
onAttach: function(worker){
worker.port.on("getWord", function(word) {
console.log(word);
worker.port.emit("newWord", word);
});
worker.port.on("updatedWord", function(URL){
console.log(URL);
});
}
});
dictionaryRef.Page({
contentScriptWhen: "ready",
contentScriptFile: [
data.url("jquery.js"),
data.url("jquery-ui.min.js"),
data.url("define.js"),
],
contentURL: "http://www.dictionary.com/browse/",
onAttach: function(worker){
worker.port.on("newWord", function(word) {
console.log(word);
self.contentURL = "http://www.dictionary.com/browse/" + word;
worker.port.emit("updatedWord", self.contentURL);
});
}
});
define.js:
$(window).dblclick(function() {
var selected = getSelected();
if (selected!="") {
calldictionary(selected);
var completedURL = "http://www.dictionary.com/browse/" + selected;
pageMod.port.emit("getWord", selected);
$('#define').dialog("open");
dictionaryRef.contentURL = completedURL;
}
});
function getSelected() {
if (window.getSelection) {
return window.getSelection().toString();
} else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
Basically, getSelected() will capture a highlighted word and then the "dblclick" binding should send a signal via port.emit() that the pageMod should receive, then pass onto a page-worker to change its URL, which would allow me to access the DOM and scrape the dictionary definition so that it can be displayed in the main window in a popup. At the moment, none of the port.emit() statements work.

Autocomplete in Jqgrid returns Data from Server but dont know to put in View

This is my first post. stackoverflow is a wonderful place for developers. Here is my issue.
I am trying to use Autocomplete in JqGrid Edit Form. i successfully retrieved data from server using ajax call but dont know how to display it in the view. below is my code.
FrontEnd Code:
colModel :[
{name:'prf_articlename', index:'prf_articlename', width:90, editable:true, edittype:'text',
editoptions: {
dataInit:function(e){
$(e).autocomplete({
source: function(request, response,term) {
var param = request.term;
$.ajax({
url: '/Myelclass/AutoCompleteServlet.do?term='+param+"&action="+"artname",
success: function (data) {
response($.map(data, function(item) {
return {
label: item.label,
};
}));//END Success
},
});//END AJAX
},
minLength: 2,
});//END AUOTOCOMPLETE
}//END Dataint
}//END Dataint
},
BackEnd Code:
String term = request.getParameter("term");
List<AutoComplete> articlelist = prfbo.getArticleNameinEditGrid(term);
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
Any one help on this???
This is what I personally use in my project:
Inside colModel:
dataInit: function (elem) { NameSearch(elem) }},
The function:
function NameSearch(elem) {
$(elem).autocomplete({ source: '/Controller/NameSearch',
minLength: 2, autosearch: true,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).focus().trigger({ type: 'keypress', charCode: 13 });
}
})//$(elem).autocomplete
$(elem).keypress(function (e) {
if (!e) e = window.event;
if (e.keyCode == '13') {
setTimeout(function () { $(elem).autocomplete('close'); }, 500);
return false;
}
})//$(elem).keypress(function (e){
} //function NameSearch(elem) {
I'm also dealing with an Enter key press as well in the above function.
here is the complete code for my Autocomplete in jqgrid Edit form..
colModel :[
{name:'name', index:'name', width:90, align:'center', editable:true, hidden: false, edittype:'text',
editoptions:{
dataInit:function (elem) {
$(elem).autocomplete({
minLength: 2,
source: function(request, response,term) {
var param = request.term; //values we enter to filter autocomplete
$.ajax({
url: "myurl",
dataType: "json",
type:"GET",
success: function (data) {
response($.map(data, function(item) {
return {
//can add number of attributes here
id: item.id,
shform: item.shortform,
value: item.name,
clr : item.color, //here apart from name and id i am adding other values too
size: item.size,
remar:item.remarks,
subs: item.subs,
selec:item.selec ,
};
}));//END Response
},//END Success
});//END AJAX
},
select: function( event, ui ) {
// setting values to textbox in jqgrid edit form based on selected values
$('#textbox1').val(ui.item.id);
$('#textbox2').val(ui.item.shform);
$('#textbox3').val(ui.item.clr);
$('#textbox4').val(ui.item.size);
$('#textbox5').val(ui.item.sizeremar);
$('#textbox6').val(ui.item.subs);
$('#textbox7').val(ui.item.selec);
$('#textbox8').val(ui.item.selp);
}
});
$('.ui-autocomplete').css('zIndex',1000); // if autocomplete has misalignment so we are manually setting it
}
}, editrules :{required : true},
formoptions:{rowpos: 1, colpos: 2}
},
........
]
server code :
String term = request.getParameter("term");
List<ArticleDetails> articlelist = prfbo.getPrfArticleName(term); //DB call via BO and DAO class
System.out.println("List Value " +articlelist.size());
JSONArray jsonOrdertanArray = JSONArray.fromObject(articlelist);
System.out.println(jsonOrdertanArray);
out.println(jsonOrdertanArray);
hope some one find it useful.

Datatables , jeditable and jquery timepicker in Zend Framework ,fnupdate unable to update old value

I have written a code to integrate timepicker with editable which is being used to make all coulmns except the hidden id coulmn and the first shown coulmn editable . I couldn't get the fnupdate make my edited coulmn to be updated to the new value when it is posted to server side . I am able to get the posted values for server side processing but the clientside is not gettting updated by fnupdate .
Please see the code below and try to tell me what i am doing wrong because i am having many pages which function the same way .
$(document).ready(function() {
oTable = $('#scheduleTable').dataTable(
{
"sDom" : '<"top"flip>rt<"bottom"<"clear">',
"bAutoWidth" : false,
"bProcessing" : true,
bJQueryUI:true,
"bServerSide": true,
"bFilter":false,
"bSort": false,
"bInfo": false,
"bPaginate":false,
"aoColumns":[
{
"bVisible" : false
},
{
},
{},
{},
{},
{}
],
"fnRowCallback" : function (nRow, aData, iDisplayIndex) {
$(nRow).attr('id', '' + aData[0]);
//i starting from one to make the first element in td non editable
for (i = 1; i < aData.length; i ++) {
$('td:eq(' + i + ') ', nRow).editable("<?= $aupdateUrl; ?>", {
'callback': function (sValue, y) {
var aPos = oTable.fnGetPosition(this);
oTable.fnUpdate(sValue, aPos[0], aPos[1]);
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
'height': '14px',
indicator : 'Saving...',
tooltip : 'Doubleclick to edit...',
type : "timepicker",
placeholder : ' '
});
}
return nRow;
},
"sAjaxSource" : "<?= $aSourceList; ?>/startdate/<?= $this->startdate; ?>"
}
);
});
$('.ui-datepicker-close').live('click', function (e){
e.preventDefault();
$('#scheduleTable tbody td input').parents("form").submit();
});
$.editable.addInputType('timepicker',{
/*create input element*/
element:function(settings,orginal){
var form = $(this),
input = $('<input type="text">');
form.append(input);
return (input);
},
plugin:function(settings,original){
/*Don't cancel inline editing onblur to allow clicking datepicker*/
settings.onblur = 'nothing';
$("input",this).filter(":text").timepicker(
{ timeFormat: 'hh:mm',
'hourMin':6,
'hourMax':21,
'showSecond': false,
'hourGrid':2,
'minuteGrid':10
}
);
}
});
I was able to solve the problem .The main thing that i was doing wrong was that i didn't have json response with only one value from my server side zend framework action.Therefore it caused the editable to function in a way that it couldn't put the value(the response) as the new value in the td element. Hope some on find it usefull peace!!

Resources