jQuery UI Autocomplete - Modification Issues - javascript

Looking at jQuery UI auto complete: http://jqueryui.com/demos/autocomplete/ and changing it to meet my requirements, I'm coming across some issues.
If you look at the default list at the link provided one of the options is "ActionScript" and if you type "Sc" it suggests "ActionScript" which in my case isn't suitable.
I only want it to suggest "ActionScript" for example if the user types:
A
Ac
Act
Acti
Actio
Action
ActionS
ActionSc
ActionScr
ActionScri
ActionScrip
ActionScript
"ActionScript" is just an example but it gets the point across.
Looking at the suggest function within jQuery UI auto complete code:
_suggest: function( items ) {
var ul = this.menu.element
.empty()
.zIndex( this.element.zIndex() + 1 );
this._renderMenu( ul, items );
// TODO refresh should check if the active item is still in the dom, removing the need for a manual deactivate
this.menu.deactivate();
this.menu.refresh();
// size and position menu
ul.show();
this._resizeMenu();
ul.position( $.extend({
of: this.element
}, this.options.position ));
if ( this.options.autoFocus ) {
this.menu.next( new $.Event("mouseover") );
}
},
I can't seem to find the part the narrows down the selections. Can someone point me in the right direction? I'm using the most recent stable build.

function hackAutocomplete(){
$.extend($.ui.autocomplete, {
filter: function(array, term){
var matcher = new RegExp("^" + term, "i");
return $.grep(array, function(value){
return matcher.test(value.label || value.value || value);
});
}
});
}
hackAutocomplete();
Found this code which solved it.

Related

Jquery Chosen plugin. Select multiple of the same option

I'm using the chosen plugin to build multiple select input fields. See an example here: http://harvesthq.github.io/chosen/#multiple-select
The default behavior disables an option if it has already been selected. In the example above, if you were to select "Afghanistan", it would be greyed out in the drop-down menu, thus disallowing you from selecting it a second time.
I need to be able to select the same option more than once. Is there any setting in the plugin or manual override I can add that will allow for this?
I created a version of chosen that allows you to select the same item multiple times, and even sends those multiple entries to the server as POST variables. Here's how you can do it (fairly easily, I think):
(Tip: Use a search function in chosen.jquery.js to find these lines)
Change:
this.is_multiple = this.form_field.multiple;
To:
this.is_multiple = this.form_field.multiple;
this.allows_duplicates = this.options.allow_duplicates;
Change:
classes.push("result-selected");
To:
if (this.allows_duplicates) {
classes.push("active-result");
} else {
classes.push("result-selected");
}
Change:
this.form_field.options[item.options_index].selected = true;
To:
if (this.allows_duplicates && this.form_field.options[item.options_index].selected == true) {
$('<input>').attr({type:'hidden',name:this.form_field.name,value:this.form_field.options[item.options_index].value}).appendTo($(this.form_field).parent());
} else {
this.form_field.options[item.options_index].selected = true;
}
Then, when calling chosen(), make sure to include the allows_duplicates option:
$("mySelect").chosen({allow_duplicates: true})
For a workaround, use the below code on each selection (in select event) or while popup opened:
$(".chosen-results .result-selected").addClass("active-result").removeClass("result-selected");
The above code removes the result-selected class and added the active-result class on the li items. So each selected item is considered as the active result, now you can select that item again.
#adam's Answer is working very well but doesn't cover the situation that someone wants to delete some options.
So to have this functionality, alongside with Adam's tweaks you need to add this code too at:
Chosen.prototype.result_deselect = function (pos) {
var result_data;
result_data = this.results_data[pos];
// If config duplicates is enabled
if (this.allows_duplicates) {
//find fields name
var $nameField = $(this.form_field).attr('name');
// search for hidden input with same name and value of the one we are trying to delete
var $duplicateVals = $('input[type="hidden"][name="' + $nameField + '"][value="' + this.form_field.options[result_data.options_index].value + '"]');
//if we find one. we delete it and stop the rest of the function
if ($duplicateVals.length > 0) {
$duplicateVals[0].remove();
return true;
}
}
....

CKEditor - remove script tag with data processor

I am quite new with CKEditor (starting to use it 2 days ago) and I am still fighting with some configuration like removing the tag from editor.
So for example, if a user type in source mode the following:
<script type="text/javascript">alert('hello');</script>
I would like to remove it.
Looking the documentation, I found that this can be done using an HTML filter. I so defined it but it does not work.
var editor = ev.editor;
var dataProcessor = editor.dataProcessor;
var htmlFilter = dataProcessor && dataProcessor.htmlFilter;
htmlFilter.addRules(
{
elements :
{
script : function(element)
{
alert('Found script :' + element.name);
element.remove();
},
img : function( element )
{
alert('Found script :' + element.name);
if ( !element.attributes.alt )
element.attributes.alt = 'Cookingfactory';
}
}
});
The img part is working well but not the script one. I guess I missed something. It even does not display the alert message for script.
Any help would be more than welcome :o)
You can use this :
CKEDITOR.replace('editor1', {
on: {
pluginsLoaded: function(event) {
event.editor.dataProcessor.dataFilter.addRules({
elements: {
script: function(element) {
return false;
}
}
});
}
}
});
If you are using CKEditor 4.1 or above, you may use Advanced Content Filter to allow the content you want.
If you are using CKEditor 4.4 or above, there is an easier way. You can use Disallowed Content to filter content you don't like .
config.disallowedContent = 'script';
As I'm having CKEditor 4, I did the next
CKEDITOR.instances.editor1.config.protectedSource.push( /{.*\".*}/g );
It will ignore quotes in smarty curly brackets

How to match multiple substrings in jQuery combobox autocomplete

I found more than a couple examples of this with a plain jquery autocomplete but not in a way that will work with the autocomplete included in the combobox code from the demo because the structure of the code is structured so differently.
I want to match every item that has all of the search tokens anywhere in any word. I don't need to match the start of any word, any part of it is fine. I don't care if the search strings are highlighted in the autocomplete list if that makes things too complicated.
Desired search/result combos: (please excuse the spacing)
"fi th" "fi rst second th ird"
"rs on" "fi rs t sec on d third"
"ec rd" "first s ec ond thi rd"
but not limited to any max/min length or number of tokens.
EDIT
I figured part of it out using the code structure from the other autocorrect I had working.
source: function( requestObj, responseFunc ) {
var matchArry = $("select > option").map(function(){return this.innerHTML;}).get();
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches
$.each (srchTerms, function (J, term) {
var regX = new RegExp (term, "i");
matchArry = $.map (matchArry, function (item) {
if( regX.test(item) ){
return{
label: item,
value: item,
option: HTMLOptionElement
} ? item :null;
}
} );
});
// Return the match results
responseFunc (matchArry);
},
and
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
$("destination").val(ui.item.value); // I added this line
},
but I can't get both multiple words AND being able to click to select working at the same time.
If I remove the } ? item :null; on the return in the map function I can click to select an item. If I leave it I can type multiple words, but I can't click any of the items...
Is that the problem or the option: this? I've tried replacing it with HTMLOptionElement and null and I'm stuck.
I am able to set the value of another field with ui.item.value within the select label but that doesn't put the value in the search box or close the dropdown menu.
On a whim I added ui.item.option = ui.item.value; to the select label and everything works as expected. the option: value in source doesn't seem to matter now.
*I make no claims that any of this is good coding practice
updated fiddle: http://jsfiddle.net/eY3hM/

Change a variable or activate a JS-linked <select> dropdown with Greasemonkey

I'm looking to change a javascript variable on page load with Greasemonkey.
The variable I'm looking to change is iDisplayLength the default value is 25, I want to change it to -1 on page load.
This is the script I tried; it did not work:
function changeTheDefaultViewVarLol() {
location.href = "javascript:void(windows.iDisplayLength = -1)";
};
changeTheDefaultViewVarLol();
Edit: From a comment below, the target page is tf2spreadsheet.blogspot.com.
The OP is actually trying to change the number of rows displayed on the page -- a function that is triggered by the "Show {x} entries" <select> dropdown.
You would just use:
unsafeWindow.iDisplayLength = -1;
No need for any of that changeTheDefaultViewVarLol() stuff.
However, this will not have the effect that you want if iDisplayLength is used by the page just after the page sets it to 25.
You will probably have to call a JS function to apply the new value. Link to the target page if this is the case.
Update for additional page information:
What you are actually trying to do is to invoke the "Show All entries" functionality of that page.
So, don't think in terms of poking JS variables, think in terms of activating whatever JS is tied to that <select>.
For a normal page similar to the one you specified, code like this would do it:
var showAllOpt = document.querySelector ('#main_table_length select option[value="-1"]');
var changeEvent = document.createEvent ("HTMLEvents");
if (showAllOpt) {
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
BUT, that page AJAXes-in the desired table long after the page "loads". So, an additional step is needed, like so:
var showAllEntriesSelect = setInterval ( function() {
setSelectValueWhenitLoads (
"#main_table_length select option",
"-1",
showAllEntriesSelect
);
}
, 200
);
function setSelectValueWhenitLoads (cssSelector, targetValue, timerVar) {
var showAllOpt = document.querySelector (
cssSelector + '[value="' + targetValue + '"]'
);
if (showAllOpt) {
clearInterval (timerVar);
showAllOpt.parentNode.selectedIndex = showAllOpt.index;
var changeEvent = document.createEvent ("HTMLEvents");
changeEvent.initEvent ("change", true, true);
showAllOpt.parentNode.dispatchEvent (changeEvent);
}
}

ExtJS Change Event Listener failing to fire

I was asked to post this as a question on StackOverflow by http://twitter.com/jonathanjulian which was then retweeted by several other people. I already have an ugly solution, but am posting the original problem as requested.
So here's the back story. We have a massive database application that uses ExtJS exclusively for the client side view. We are using a GridPanel (Ext.grid.GridPanel) for the row view loaded from a remote store.
In each of our interfaces, we also have a FormPanel (Ext.form.FormPanel) displaying a form that allows a user to create or edit records from the GridPanel. The GridPanel columns are bound to the FormPanel form elements so that when a record is selected in the GridPanel, all of the values are populated in the form.
On each form, we have an input field for the table row ID (Primary Key) that is defined as such:
var editFormFields = [
{
fieldLabel: 'ID',
id: 'id_field',
name: 'id',
width: 100,
readOnly: true, // the user cannot change the ID, ever.
monitorValid: true
} /* other fields removed */
];
So, that is all fine and good. This works on all of our applications. When building a new interface, a requirement was made that we needed to use a third-party file storage API that provides an interface in the form of a small webpage that is loaded in an IFrame.
I placed the IFrame code inside of the html parameter of the FormPanel:
var editForm = new Ext.form.FormPanel({
html: '<div style="width:400px;"><iframe id="upload_iframe" src="no_upload.html" width="98%" height="300"></iframe></div>',
/* bunch of other parameters stripped for brevity */
});
So, whenever a user selects a record, I need to change the src attribute of the IFrame to the API URL of the service we are using. Something along the lines of http://uploadsite.com/upload?appname=whatever&id={$id_of_record_selected}
I initially went in to the id field (pasted above) and added a change listener.
var editFormFields = [
{
fieldLabel: 'ID',
id: 'id_field',
name: 'id',
width: 100,
readOnly: true, // the user cannot change the ID, ever.
monitorValid: true,
listeners: {
change: function(f,new_val) {
alert(new_val);
}
}
} /* other fields removed */
];
Nice and simple, except that it only worked when the user was focused on that form element. The rest of the time it failed to fire at all.
Frustrated that I was past a deadline and just needed it to work, I quickly implemented a decaying poller that checks the value. It's a horrible, ugly hack. But it works as expected.
I will paste my ugly dirty hack in an answer to this question.
"The GridPanel columns are bound to
the FormPanel form elements so that
when a record is selected in the
GridPanel, all of the values are
populated in the form."
As I understand it from the quote above, the rowclick event is what actually triggers the change to your form in the first place. To avoid polling, this could be the place to listen, and eventually raise to your custom change event.
Here is the ugly hack that I did to accomplish this problem:
var current_id_value = '';
var check_changes = function(offset) {
offset = offset || 100;
var id_value = document.getElementById('id_field').value || '';
if ( id_value && ( id_value != current_id_value ) ) {
current_id_value = id_value;
change_iframe(id_value);
} else {
offset = offset + 50;
if ( offset > 2500 ) {
offset = 2500;
}
setTimeout(function() { check_changes(offset); }, offset);
}
};
var change_iframe = function(id_value) {
if ( id_value ) {
document.getElementById('upload_iframe').src = 'http://api/upload.php?id=' + id_value;
} else {
document.getElementById('upload_iframe').src = 'no_upload.html';
}
setTimeout(function() { check_changes(100); }, 1500);
};
It's not pretty, but it works. All of the bosses are happy.
If you took a moment to read the source, you would see that the Ext.form.Field class only fires that change event in the onBlur function

Categories

Resources