Jquery trigger with data passed not working with on and blur - events

I dont know why the blur method is not receiving the passed data when using on and a selector.
Here is the code, just foucs any input, and press tab, and you will see that the isTab parameter is not being setted. Why?
Fiddle:
http://jsfiddle.net/fz5yA/9/
Html:
<div id="Container">
</div>
JavaScript:
var Container = $("#Container");
Container.on({
keydown : function(e){
var Item = $(this);
console.log(e.keyCode);
if(e.keyCode == 9) {
Item.trigger("blur",[true]);
return false;
}
},
blur : function(e, isTab)
{
console.log("IsTab:" + isTab);
}},".Item");
for(var i = 0 ; i < 10 ; i++)
{
Container.append("<input class='Item'/>");
Container.append("<br/>");
}

The system generated blur event just has one argument, not two. There is no isTab argument passed to that event handler in the normal way that the system creates that event. You can see that in the jQuery doc.
If you change the event name of your manually triggered event to something that isn't the normal blur event and you fix the way you are passing the argument in .trigger(), then the extra argument will work. Change to this and you will see the extra argument:
Container.on({
keydown : function(e){
var Item = $(this);
console.log(e.keyCode);
if(e.keyCode == 9) {
console.log("aaa");
Item.trigger("myEvent", true); // Changed event name and fixed the syntax in this line
return false;
}
},
myEvent : function(e, isTab) // Changed event name here
{
console.log("IsTab:" + isTab);
}},".Item");
Demo here: http://jsfiddle.net/jfriend00/fz5yA/17/

Related

jqgrid - Add new row and disable restoreRow function

If I will add new row and I will enable automatic editing newly added row, then I want to perform validation and save row by ENTER button, BUT I don't want to restore row by ESC button. Because I set required: true by all fields and If newly added row will be to have empty at least one field, then ESC button (restoreRow) causes inconsistency my data, because will not be performed validation and newly added row will be to have empty fields. Although I set required: true.
The problem is that After added new row I always want to validate the edited row before saving, but ESC button causes restoreRow. For normal editing causes by doubliClick I want use ESC for restore row and ENTER for save row.
My code is generated from coffeescript
$("#add-row").click((function(_this) {
return function(e) {
e.preventDefault();
return _this.saveEditingRow(function() {
var dataIds;
_this.table.jqGrid("addRowData", void 0, "last");
dataIds = _this.table.jqGrid("getDataIDs");
if (dataIds.length > 0) {
return _this.table.jqGrid("editRow", dataIds[dataIds.length - 1], {
keys: true,
url: "clientArray",
aftersavefunc: function(rowId) {
return retypeColumnValues.call(table, rowId);
}
});
}
});
};
})(this));
Table.prototype.saveEditingRow = function(successfunc, errorfunc) {
var i, result, savedRows, success, _i, _ref;
savedRows = this.table.jqGrid("getGridParam", "savedRow");
success = true;
for (i = _i = 0, _ref = savedRows.length; _i < _ref; i = _i += 1) {
if (savedRows.length > 0) {
result = this.table.jqGrid("saveRow", savedRows[i].id, {
url: "clientArray"
});
if (!result && success) {
success = false;
}
}
}
if (success) {
return typeof successfunc === "function" ? successfunc() : void 0;
} else {
return typeof errorfunc === "function" ? errorfunc() : void 0;
}
};
If it will be necessary, I will fill all code in coffeescript.
I agree that it's a problem because the option keys: true register keydown event handler which process both Enter and Esc. You can't just inform jqGrid to process Enter, but don't process Esc.
If you don't call restoreRow in your code then you could probably salve your problem by usage of beforeCancelRow callback which you could define in $.jgrid.inlineEdit.
$.extend(true, $.jgrid.inlineEdit, {
beforeCancelRow: function () { // the parameters options and rowid can be used
return false;
}
});
The code above will don't allows restoreRow at all. You can modify the code by including some validations.
One more options which you have: don't use keys: true, but register your own keydown handler on all <input> and <select> fields in the editing row. You can do this inside of oneditfunc callback. See the source code of keydown handler used by jqGrid. You need just call of saveRow in case of e.keyCode === 13. The required rowid you can either get from the outer scope (if you do this inside of oneditfunc) or to get it from e.target: $(e.target).closest("tr.jqgrow").attr("id").
One more option: you can add some class like jqgrid-new-row (it's the class used by addRow method) to the row (<tr>) directly after call of addRowData ($("#" + dataIds[dataIds.length - 1]).addClass("jqgrid-new-row")). You should add afterrestorefunc callback to editRow which you call. Inside of the afterrestorefunc you can test whether the row has jqgrid-new-row class and call delRowData row in the case. By the way if you add the class with jqgrid-new-row name (or to use addRow instead of addRowData) then deleting of canceled row will be done automatically by restoreRow (see the code fragment).
You can even do this unconditionally without any tests for the class jqgrid-new-row if the above code work only in case of editing of new added row. So the call of editRow could be like below
return _this.table.jqGrid("editRow", dataIds[dataIds.length - 1], {
keys: true,
url: "clientArray",
aftersavefunc: function(rowId) {
return retypeColumnValues.call(table, rowId);
},
afterrestorefunc: function(rowId) {
_this.table.jqGrid("delRowData", rowId); // delete after cancel editing
}
});

KnockoutJS not calling update function in custom binding handler

I have written a multiselect jQuery plugin that can be applied to a normal HTML select element.
However, this plugin will parse the select element and its options and then remove the select element from the DOM and insert a combination of divs and checkboxes instead.
I have created a custom binding handler in Knockout as follows:
ko.bindingHandlers.dropdownlist = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
// Retrieve the value accessor
var value = valueAccessor();
// Get the true value of the property
var unwrappedValue = ko.utils.unwrapObservable(value);
// Check if we have specified the value type of the DropDownList items. Defaults to "int"
var ddlValueType = allBindingsAccessor().dropDownListValueType ? allBindingsAccessor().dropDownListValueType : 'int';
// Check if we have specified the INIMultiSelect options otherwise we will use our defaults.
var elementOptions = allBindingsAccessor().iniMultiSelectOptions ? allBindingsAccessor().iniMultiSelectOptions :
{
multiple: false,
onItemSelectedChanged: function (control, item) {
var val = item.value;
if (ddlValueType === "int") {
value(parseInt(val));
}
else if (ddlValueType == "float") {
value(parseFloat(val));
} else {
value(val);
}
}
};
// Retrieve the attr: {} binding
var attribs = allBindingsAccessor().attr;
// Check if we specified the attr binding
if (attribs != null && attribs != undefined) {
// Check if we specified the attr ID binding
if (attribs.hasOwnProperty('id')) {
var id = attribs.id;
$(element).attr('id', id);
}
if (bindingContext.hasOwnProperty('$index')) {
var idx = bindingContext.$index();
$(element).attr('name', 'ddl' + idx);
}
}
if ($(element).attr('id') == undefined || $(element).attr('id') == '') {
var id = "ko_ddl_id_" + (ko.bindingHandlers['dropdownlist'].currentIndex);
$(element).attr('id', id);
}
if ($(element).attr('name') == undefined || $(element).attr('name') == '') {
var name = "ko_ddl_name_" + (ko.bindingHandlers['dropdownlist'].currentIndex);
$(element).attr('name', name);
}
var options = $('option', element);
$.each(options, function (index) {
if ($(this).val() == unwrappedValue) {
$(this).attr('selected', 'selected');
}
});
if (!$(element).hasClass('INIMultiSelect')) {
$(element).addClass('INIMultiSelect');
}
$(element).iniMultiSelect(elementOptions);
ko.bindingHandlers['dropdownlist'].currentIndex++;
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var unwrappedValue = ko.utils.unwrapObservable(valueAccessor());
var id = $(element).attr('id').replace(/\[/gm, '\\[').replace(/\]/gm, '\\]');
var iniMultiSelect = $('#' + id);
if (iniMultiSelect != null) {
iniMultiSelect.SetValue(unwrappedValue, true);
}
}};
ko.bindingHandlers.dropdownlist.currentIndex = 0;
This will transform the original HTML select element into my custom multiselect.
However, when the update function is called the first time, after the init, the "element" variable will still be the original select element, and not my wrapper div that holds my custom html together.
And after the page has been completely loaded and I change the value of the observable that I am binding to, the update function is not triggered at all!
Somehow I have a feeling that knockout no longer "knows" what to do because the original DOM element that I'm binding to is gone...
Any ideas what might be the issue here?
There is clean up code in Knockout that will dispose of the computed observables that are used to trigger bindings when it determines that the element is no longer part of the document.
You could potentially find a way to just hide the original element, or place the binding on a container of the original select (probably would be a good option), or reapply a binding to one of the new elements.
I ran into a similar problem today, and here's how I solved it. In my update handler, I added the following line:
$(element).attr("dummy-attribute", ko.unwrap(valueAccessor()));
This suffices to prevent the handler from being disposed-of by Knockout's garbage collector.
JSFiddle (broken): http://jsfiddle.net/padfv0u9/
JSFiddle (fixed): http://jsfiddle.net/padfv0u9/2/

Qooxdoo Multiple Buttons save by ID

I using the following:
var list = [];
lin = new gui.AWindow();
Len = list.length;
lin.add(Len+1);
list[Len] = "close button";
multiple times to generate new rows of buttons in the window. I want the event handlers when the button is clicked to give its row number.
qx.Class.define("gui.AWindow",
{
extend : qx.ui.window.Window,
events :
{
"execute" : "qx.event.type.Data"
},
members :
{
add : function()
{
closeButton = new qx.ui.toolbar.Button("CLOSE");
lin.add(closeButton,{row: Pos+1, column: 0});
closeButton.addListener("execute", function(e)
{
this.debug(e.getData());
}, this);
}
},
construct : function()
{
this.base(arguments, "gui");
// hide the window buttons
this.setShowClose(false);
this.setShowMaximize(false);
this.setShowMinimize(false);
//adjust size
this.setWidth(250);
this.setHeight(300);
var layout = new qx.ui.layout.Grid(0, 0);
this.setLayout(layout);
}
});
If you use a qx.data.Array instead of using a standard JS list then you can use the indexOf method to find the index of the button in the array.
In your event handler you can use qx.event.type.Event.getTarget() method to get a reference to the widget that fired the event and pass that to the indexOf method.

jqGrid - Inline edit - Detect dirty / changed cells

is there an example of using jqgrid's getChangedCells
method to determine if data has changed?
I grepped getChangedCells in the downloadable demos for
jqgrid, and could only find the function definition, not
example usages of getChangedCells.
What I want to do is save the edits that a user's
made if the user clicks on another row. But, I only
want to submit the save if the row is dirty.
Thanks in advance,
--Nate
There are no safe dirty flag on the row. You can use the fact that at the beginning of row editing (at the start of the inline editing mode) the method editRow add editable="1" attribute to the grid row (<tr> element). Later the methods saveRow and restoreRow changes the attribute value to editable="0". So the rows of the current page which was at least once in the inline editing mode will have the editable attribute. If the id of the table element is "list" you can find the edited rows with
$("#list tr[editable]")
The ids of the elements of the set are the rowids of the rows.
If you use paging in the grid you should be careful and save the ids of the edited rows on the current page before the changing of the page. The onPaging event would help you here.
In my opinion the best and the most safe way to do what you need is to use aftersavefunc parameter of the editRow or saveRow methods (probably you use directly only editRow). Inside of your aftersavefunc function you can save the id of the modified row in an array/map. This will solve your problem and will safe work.
Finally, I managed to bring a piece of code to detect what we want ;)
Hopefully any jqgrid gurus there (like Oleg), have enough time to review this code and improve it.
The example code will work for detect data changed in a grid with an editable field named "name". If you want to check for changed data in more columns, you have to add the variables after_edit and before_edit asociated with that columns.
To get the previous cell data inside the onSelectRow function, I don't used the getCell method because in the documentation says in red:
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
By disgrace I could check that the documentation was right :(.
However the getCell function works properly with the current cell data.
And here is the code:
// Declare variables used for inline edit functionality.
var last_selected;
var before_edit_value;
var after_edit_value;
$('#grid-id').jqGrid({
...
onSelectRow: function(row_id){
if(row_id && row_id !== last_selected) {
/*
* Determine if the value was changed, if not there is no need to save to server.
*/
if (typeof(last_selected) != 'undefined') {
after_edit_value = $('#grid-id tr#' + last_selected + ' .name_column input').val();
}
if (before_edit_value != after_edit_value) {
/*
* Save row.
*/
$('#grid-id').jqGrid(
'saveRow',
last_selected,
function(response){
/* SuccessFunction: Do something with the server response */
return true;
},
'http://url.to.server-side.script.com/server-side-script.php',
{
additional_data: 'example: additional string',
});
}
else {
/*
* Restore the row.
*/
$('#grid-id').jqGrid('restoreRow', last_selected);
}
before_edit_value = $('#grid-id').jqGrid('getCell', row_id, 'name');
}
last_selected = row_id;
/*
* Edit row.
*/
$('#grid-id').jqGrid(
'editRow',
row_id,
true,
function() {/* OnEditFunction */},
function(response) {
/* SuccessFunction: Do something with the server response */
return true;
},
'http://url.to.server-side.script.com/server-side-script.php',
{
additional_data: 'example: additional string',
});
},
...
});
In one of my projects I did the following: before editing the row I remember row data in global variable and after editing is done just check if row data was changed. Something like this (edit mode activated by double click):
var beforeEditData;
function onGridDblClickRow(id) {
if (isRowEditable(id)) {
beforeEditData = grid.getRowData(id);
grid.editRow(id, true, null, null, 'clientArray', null, onRowAfterEdit);
...
}
}
function onRowAfterEdit(row) {
var data = grid.getRowData(row);
if (!isDataChanged(beforeEditData, data)) {
return; // No changes
}
... // Save data here
}
function isDataChanged(before, after){
... // Allows tricky logic for dirty data, e.g. one may trim spaces etc.
}
Using MVC4 and JQuery this is what I did
In the View
<script type="text/javascript">
var $grid = $("#Grid");
var lastSelection;
var datachanged = false;
function gridInitialised() {
var headers = $('th>div>:input');
for (var h = 0; h < headers.length; headers[h++].onclick = (function () { if (datachanged) { $grid.saveRow(lastSelection); datachanged = false; } }));
}
function editRow(id) {
if (id && id !== lastSelection) {
if (datachanged) { $grid.saveRow(lastSelection); datachanged = false; }
$grid.restoreRow(lastSelection);
$grid.editRow(id, true);
var inputs = $('#'+id+'>td>:input[class="editable"]');
for (var i = 0; i < inputs.length; inputs[i++].onchange = (function () { datachanged = true; }));
lastSelection = id;
}
}
</script>
#Html.Trirand().JQGrid(Model.Grid, "Grid")
in the Model
Grid.ClientSideEvents.RowSelect = "editRow";
Grid.ClientSideEvents.GridInitialized = "gridInitialised";
The gridInitialised code is to handle changes to the search filter.
Dave
As Oleg mentioned 5 (wow) years ago - I used the saveRow function and passed the flag as extraparam.
something like this, assuming your "model" or a hidden column IsDirty in my case:
onSelectRow: function(id) {
if (id && id !== lastgridsel) {
$("#myGrid").saveRow(lastgridsel, false, "clientArray", { IsDirty: "True" });
$("#myGrid").editRow(id, true, null, null, "clientArray");
lastgridsel = id;
}
},
and then loop through the rows on Save click (external button in my case), something along the lines of:
$("#gridSaveBtn").on("click", function() {
var batch = new Array();
var dataIds = $("#myGrid").jqGrid("getDataIDs");
for (var i = 0; i < dataIds.length; i++) {
try {
$("#myGrid").jqGrid("saveRow", dataIds[i], false, "clientArray");
//get row data
var data = $("#myGrid").jqGrid("getRowData", dataIds[i]);
if (data["IsDirty"] === "True") {
batch.push(data);
}
} catch (ex) {
alert(ex.Message);
$("#myGrid").jqGrid("restoreRow", dataIds[i]);
}
}
});

Change text in Div using jQuery, MetaData and Map highlights

I'm a newbie to jQuery and I have a map with a highlight plugin, when mouse over an area I want to change the text in a div with an ID and the text I will get it from the area attribute Alt="some text"
Here is the code that used for area loops, I'm pretty sure I can add a small function here but I couldn't figure it out.
//map
clicks$(".tabs area").click(function(){
//areas loop:
$(".tabs area").each(function(){
var d = $(this).data('maphilight') || {};
if(d.alwaysOn == true){
d.alwaysOn = false;
}
});
var data = $(this).data('maphilight') || {};
data.alwaysOn = true;
$(this).data('maphilight', data).trigger('alwaysOn.maphilight');
if ($(this).hasClass("current") == false)
{
var thisTarget = $(this).attr("href");
$(this).parents(".tabs").find('area.current').removeClass('current');
$(this).addClass('current');
$(this).parents(".tabs").nextAll(".tab-content").children(":visible").fadeOut(1, function() {
$(thisTarget).fadeIn("fast");
});
}
return false;
});
Any help or suggestions on how I can get this done would be highly appreciated.
I'm not familiar with the highlights plugin, but I think you just wanna add a mouseover event to each area like so (you would place this before/after your .click declaration):
$(".tabs area").mouseover(function() {
var alt_text = $(this).attr('alt');
$("#YOUR_TEXT_DIV_ID").html(alt_text);
}).mouseout(function() {
//do something on mouseout
});

Resources