How to prevent onSelect to fire on already selected item - javascript

I use autosuggestion plugin.
First I have code:
$('.auto').autocomplete({
lookup: data,
onSelect: function (suggestion) {
console.log(koji);
$('#cena_'+koji).val(suggestion.cena);
console.log(suggestion.ID);
$('#jmere'+koji).val(suggestion.jmere);
$('#kol'+koji).val(suggestion.kol);
$('#popust'+koji).val(suggestion.popust);
$('#pdv'+koji).val(suggestion.porez);
etc...
and this is OK, so when I pick some Item from list I update other input fields.
But after that I just choose other value for #cena or #jmere but if I click again on input field with class .auto (that is picked before), then onSelect is again fired and values I choose manualy #cena or #jmere been changed to suggested values.
Please help me to solve this problem. So how I can prevent call onSelect when there is already picked Item...
The JS code of onSelect is:
onSelect: function (index) {
var that = this,
onSelectCallback = that.options.onSelect,
suggestion = that.suggestions[index];
that.currentValue = that.getValue(suggestion.value);
if (that.currentValue !== that.el.val() && !that.options.preserveInput) {
that.el.val(that.currentValue);
}
that.signalHint(null);
that.suggestions = [];
that.selection = suggestion;
if ($.isFunction(onSelectCallback)) {
onSelectCallback.call(that.element, suggestion);
}
},
So is there any way to change onSelect option - to prevent calling when there is already picked some item?

You can disable the autocomplete by using disable:
$('SELECTOR').autocomplete('disable');
And you can change it back like:
$('SELECTOR').autocomplete('enable');
jsfiddle DEMO
If you want to completely remove the autocomplete you can use despose ad OP said:
$('SELECTOR').autocomplete('dispose');

Related

Jquery select2 - How to disable options in one dropdown without affecting all other dropdowns?

This is what I'm doing:
$('select').each(function () {
var selectedValue = $(this).find('option:selected').val();
if (selectedValue !== '0') {
$('option').each(function () {
if (!this.selected) {
$(this).attr('disabled', true);
}
});
}
});
The first option is "-Select an option-" that has a value of "0", that's why I do that validation. Basically what I want to do is to disable all options within a dropdown that has a selected value different than the first one. All dropdowns have been initialized with jquery's select2 and every one of them has a unique id.
The code I'm sharing doesn't work properly because I get the options disabled in every dropdown no matter if no option has been selected.
Can anybody help me fix this please?
I haven't tested but you should replace this line:
$('option').each(function () {
with this one:
$(this).find('option').each(function () {
Also, you should call this function using change event, which means i'ts triggered when some option is selected, like this:
$('select').on('change', function() {
The thing is that by doing this:
$('select').each(function () {
$('option').each(function () {
You were iterating through all select elements and all it's options, instead of iterating through the only select element that was clicked

Avoid clicking twice to begin editing boolean (checkbox) cell in Backgrid

We are using Backgrid and have discovered that to begin editing a "boolean" (checkbox) cell in Backgrid, you must click twice: the first click is ignored and does not toggle the state of the checkbox. Ideally we would get to the root of what is causing this behavior (e.g. is preventDefault being called) and solve it there, but I at first I tried a different approach with the following extension of BooleanCell's enterEditMode method which seemed like a logical place since it was upon entering edit mode that the checkbox click was being ignored.
Problem is my attempt also toggles the state of the previously edited checkbox. Here is the code.
var BooleanCell = Backgrid.BooleanCell.extend({
/*
* see https://github.com/wyuenho/backgrid/issues/557
*/
enterEditMode: function () {
Backgrid.BooleanCell.prototype.enterEditMode.apply(this, arguments);
var checkbox = this.$('input');
checkbox.prop('checked', !checkbox.prop('checked'));
}
});
The following seems to work:
var BooleanCell = Backgrid.BooleanCell.extend({
editor: Backgrid.BooleanCellEditor.extend({
render: function () {
var model = this.model;
var columnName = this.column.get("name");
var val = this.formatter.fromRaw(model.get(columnName), model);
/*
* Toggle checked property since a click is what triggered enterEditMode
*/
this.$el.prop("checked", !val);
model.set(columnName, !val);
return this;
}
})
});
This is because the render method gets called by Backgrid.BooleanCell's enterEditMode method on click, and said method destroys and re-creates the checkbox as follows but in so doing loses the checked state (after the click) of the original "non-edit-mode" checkbox
this.$el.empty();
this.$el.append(this.currentEditor.$el);
this.currentEditor.render();
A simpler approach:
var OneClickBooleanCell = Backgrid.BooleanCell.extend({
events: {
'change input': function(e) {
this.model.set(this.column.get('name'), e.target.checked);
},
},
});
This bypasses the CellEditor mechanism entirely and just reacts to the input event on the checkbox by updating the model.

Kendo UI grid filtering via DropDownList instead of MultiSelect

The following snippet uses a MultiSelect field to filter through an array of items. Filtering only occurs when items have been selected in the MultiSelect and the 'Filter' button has been clicked.
http://jsbin.com/iVIQoKiV/1/edit
How can it be set up using a DropDownList instead? Also, once an item has been selected in the DropDownList, how can the grid be filtered instantly without the need to click a button?
Edit:
Here's a new JSBin. Managed to implement a DropDownList. I've used the following change event but now filtering doesn't work:
change: function() {
var value = dropdown.value();
if (value) {
grid.data("kendoGrid").dataSource.filter({
field: "Territories",
operator: function (itemValue) {
var matchingItem = itemValue.find(function (item) {
return $.inArray(item.TerritoryID, value) >= 0;
});
return matchingItem !== null;
}
});
}
Hello just the same scenario is covered in the Toolbar Grid online demo here. It filters instantly beucase it uses the change event of the DropDownList to invoke the filter method immediately.

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Tooltip of previous onValidationError event displayed even when correct values are entered in the slickgrid node

I am using requiredFieldValidator for my TextEditor. Using the onValidationError event as given below, i set the title attribute of my cell to the error message so that a tooltip will be displayed as 'This is a required field'.
var handleValidationError = function(e, args) {
var validationResult = args.validationResults;
var activeCellNode = args.cellNode;
var editor = args.editor;
var errorMessage = validationResult.msg
$(activeCellNode).live('mouseover mouseout', function(event) {
if (event.type == 'mouseover') {
$(activeCellNode).attr("title", errorMessage);
} else {
$(activeCellNode).attr("title", "");
}
});
grid.onValidationError.subscribe(handleValidationError);
Successfully, the tooltip is displayed when there is some validation error.
But the problem is When the same cell is given a correct value and validation succeeds, the previous tooltip appears again.
How do I remove that tooltip on successful validation?
I have found a solution for this issue and it works fine.
By going through the slick.grid.js code, i understood that OnValidationError event will be triggered only when the 'valid' value from the validator is false.
My idea was to fire the onValidationError event whenever validator is called i.e on both validation success and failure, and to check for 'valid' value and handle the tooltip according to that value.
STEPS:
In slick.grid.js, I added the trigger for onValidationError event when 'valid' from validator is true also.
(i.e) add the below given code before return statement in if(validationResults.valid) in slick.grid.js
trigger(self.onValidationError, {
editor: currentEditor,
cellNode: activeCellNode,
validationResults: validationResults,
row: activeRow,
cell: activeCell,
column: column
});
2. In the onValidationError event handler of your slickgrid,get the value of the parameter 'valid'. If true, it means validation is success and remove tooltip i.e remove
title attribute for that node. If 'valid' is false, it means
validation has failed and add tooltip.i.e set the title attribute to
error message. By doing this, the tooltip of the previous
onValidationError will not appear on the same node. The code goes as
follows:
grid.onValidationError.subscribe(function(e, args) {
var validationResult = args.validationResults;
var activeCellNode = args.cellNode;
var editor = args.editor;
var errorMessage = validationResult.msg;
var valid_result = validationResult.valid;
if (!valid_result) {
$(activeCellNode).attr("title", errorMessage);
}
else {
$(activeCellNode).attr("title", "");
}
});
Hope this solution will help others for this issue.
HAPPY LEARNING!!!
Rather than editing the slick grid js - I've submitted a request for this change - in the meantime you can subscribe to the following events to remove the previous validation display:
grid.OnCellChange.Subscribe(delegate(EventData e, object a)
{
// Hide tooltip
});
grid.OnActiveCellChanged.Subscribe(delegate(EventData e, object a)
{
// Hide tooltip
});
grid.OnBeforeCellEditorDestroy.Subscribe(delegate(EventData e, object a)
{
// Hide tooltip
});
A much more appropriate way to implement this is to subscribe to the onBeforeCellEditorDestroy event and clean up the state (i.e. clear the tooltip) there.
I wasn't able to determine the current cell in OnBeforeCellEditorDestroy, so I just cleared the title in onCellChange, which fires before onValidationError. For example:
grid.onCellChange.subscribe(function (e, args) {
$(grid.getCellNode(args.row, args.cell)).children("input").attr( "title", "");
});

Categories

Resources