jQuery autocomplete: want to change the input field's value and retrigger the search - jquery-autocomplete

I have this nice working autocomplete using the Rails3 jQuery auto-complete plugin, but in an "after-hook" (don't know if this is the right description for it) I want to alter the value and retrigger the autocomplete.
<script type="text/javascript" charset="utf-8">
$('#position_name').bind('railsAutocomplete.select', function(event, data) {
// Remove the placeholder from the value and set selection range into it!
if(this.value.indexOf('"(.+)"') >= 0) {
placeholder_content_index = this.value.length - 5;
this.value = this.value.substr(0, placeholder_content_index) + '"';
this.setSelectionRange(placeholder_content_index, placeholder_content_index);
}
});
</script>
So far everything works except retriggering the autocomplete call. I've tried stuff like $("#position_name").change();, this.change(), this.trigger("change"), etc., but it didn't work. Thanks a lot for pointing me into the right direction!

Related

Wordpress Technical Terms

I'm working on designing a site in WP, but I'm at a loss for the right words to google. What I'm looking for is a "text container that can be toggled". I have a syntax highlighting plugin for posting code, but I don't want the code to be visible in large blocks considering it may be a little distracting. I was wondering if anyone could link me to a plugin or give me the technical term for what I'm thinking of, where you can put the text in a group and then be able to toggle whether it is visible or not within the page.
It sounds like what you are looking for is simply applying a CSS class to the element and then using jQuery or some other JS library to toggle its visibility. Example below (code is not optimized in order to explain some of the concepts. This can, read "should", be cleaned up):
// This is HTML/CSS
<body>
...
<p>Here is some normal text.</p>
Show/hide source code for displayText method
<div class="source_code" id="source_code_for_displayText_method">
// Groovy code
...
public void displayText(String message) {
outputStream.write(message)
}
...
</div>
...
Show/hide source code for download method
<div class="source_code" id="source_code_for_download_method">
// Groovy code
...
GParsPool.withPool(threads) {
sessionDownloadedFiles = localUrlQueue.collectParallel { URL url ->
downloadFileFromURL(url)
}
}
...
</div>
...
Show/hide all source code sections
...
</body>
You can default all source code sections to hidden:
// This is CSS
.source_code {
display: hidden;
}
Then you would use JS to provide the toggle ability:
// This is JavaScript
// This toggles a specific section by using an id ("#") selector
$('#source_code_displayText_method_toggle_link').onClick(function() {
$('#source_code_for_displayText_method').toggle();
});
// This toggles all source code sections by using a class (".") selector
$('#source_code_all_toggle_link').onClick(function() {
$('.source_code').toggle();
});
Some thoughts:
If you toggle all sections, you need to determine what the current state is -- if some are currently shown and others hidden, this will invert each. If you want "hide all" and "show all", then use .hide() and .show() respectively.
If you are manually adding the source code sections and want semantic selectors, the above is fine. If you are building some kind of automation/tool to allow you to repeat this, you'll probably want to use generated ids and helper links, in which case it would look like:
.
// This is HTML/CSS
<body>
...
<p>Here is some normal text.</p>
Show/hide source code for displayText method
<div class="source_code" id="source_code_1">
// Groovy code
...
public void displayText(String message) {
outputStream.write(message)
}
...
</div>
...
Show/hide source code for download method
<div class="source_code" id="source_code_2">
// Groovy code
...
GParsPool.withPool(threads) {
sessionDownloadedFiles = localUrlQueue.collectParallel { URL url ->
downloadFileFromURL(url)
}
}
...
</div>
...
Show/hide all source code sections
...
</body>
With the JavaScript to handle id parsing:
// This is JavaScript
// This toggles a specific section by using a dynamic id ("#") selector
$('.source_code_toggle_link').onClick(function(elem) {
var id = $(elem).attr("id");
// Split on the _ and take the last element in the resulting array
var idNumber = id.split("_")[-1];
var codeBlock = $('#source_code_' + idNumber);
codeBlock.toggle();
});

Paste as plain text Contenteditable div & textarea (word/excel...)

I would like the to paste text in a contenteditable div, but reacting as a textarea.
Note that I want to keep the formatting as I would paste it in my textarea (from word, excel...).
So.
1) Paste text in contenteditable div
2) I get the text from clipboard
3) I push my value from clipboard to my textarea, (dont know how??)
4) Get value from my textarea and place it in my contenteditable div
Any suggestions?
I'm CKEditor's core developer and by coincidence for last 4 months I was working on clipboard support and related stuff :) Unfortunately I won't be able to describe you the entire way how pasting is handled, because the tales of the impl are too tricky for me even after writing impl by myself :D
However, here're some hints that may help you:
Don't write wysiwyg editor - use one that exists. It's going to consume all your time and still your editor will be buggy. We and guys from other... two main editors (guess why only three exist) are working on this for years and we still have full bugs lists ;).
If you really need to write your own editor check out http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/clipboard/plugin.js - it's the old impl, before I rewrote it, but it works everywhere where it's possible. The code is horrible... but it may help you.
You won't be possible to handle all browsers by just one event paste. To handle all ways of pasting we're using both - beforepaste and paste.
There's number (huge number :D) of browsers' quirks that you'll need to handle. I can't to describe you them, because even after few weeks I don't remember all of them. However, small excerpt from our docs may be useful for you:
Paste command (used by non-native paste - e.g. from our toolbar)
* fire 'paste' on editable ('beforepaste' for IE)
* !canceled && execCommand 'paste'
* !success && fire 'pasteDialog' on editor
Paste from native context menu & menubar
(Fx & Webkits are handled in 'paste' default listner.
Opera cannot be handled at all because it doesn't fire any events
Special treatment is needed for IE, for which is this part of doc)
* listen 'onpaste'
* cancel native event
* fire 'beforePaste' on editor
* !canceled && getClipboardDataByPastebin
* execIECommand( 'paste' ) -> this fires another 'paste' event, so cancel it
* fire 'paste' on editor
* !canceled && fire 'afterPaste' on editor
The rest of the trick - On IEs we listen for both paste events, on the rest only for paste. We need to prevent some events on IE, because since we're listening for both sometimes this may cause doubled handling. This is the trickiest part I guess.
Note that I want to keep the formatting as I would paste it in my textarea (from word, excel...).
Which parts of formatting do you want to keep? Textarea will keep only basic ones - blocks formatting.
See http://dev.ckeditor.com/browser/CKEditor/trunk/_source/plugins/wysiwygarea/plugin.js#L120 up to line 123 - this is the last part of the task - inserting content into selection.
Current solution works perfect in IE/SAF/FF
But still i need a fix for "non" keyboard events, when pasting with mouse click...
Current solution for keyboard "paste" events:
$(document).ready(function() {
bind_paste_textarea();
});
function bind_paste_textarea(){
var activeOnPaste = null;
$("#mypastediv").keydown(function(e){
var code = e.which || e.keyCode;
if((code == 86)){
activeOnPaste = $(this);
$("#mytextarea").val("").focus();
}
});
$("#mytextarea").keyup(function(){
if(activeOnPaste != null){
$(activeOnPaste).focus();
activeOnPaste = null;
}
});
}
<h2>DIV</h2>
<div id="mypastediv" contenteditable="true" style="width: 400px; height: 400px; border: 1px solid orange;">
</div>
<h2>TEXTAREA</h2>
<textarea id="mytextarea" style="width: 400px; height: 400px; border: 1px solid red;"></textarea>
I have achieved this using rangy library to save and restore selections.
I also perform some other work using the library in the same functions, which I have stripped out of this example, so this is not optimal code.
HTML
<div><div id="editor"contenteditable="true" type="text"></div><div>
Javascript
var inputArea = $element.find('#editor');
var debounceInterval = 200;
function highlightExcessCharacters() {
// Bookmark selection so we can restore it later
var sel = rangy.getSelection();
var savedSel = sel.saveCharacterRanges(editor);
// Strip HTML
// Prevent images etc being pasted into textbox
inputArea.text(inputArea[0].innerText);
// Restore the selection
sel.restoreCharacterRanges(editor, savedSel);
}
// Event to handle checking of text changes
var handleEditorChangeEvent = (function () {
var timer;
// Function to run after timer passed
function debouncer() {
if (timer) {
timer = null;
}
highlightExcessCharacters();
}
return function () {
if (timer) {
$timeout.cancel(timer);
}
// Pass the text area we want monitored for exess characters into debouncer here
timer = $timeout(debouncer, debounceInterval);
};
})();
function listen(target, eventName, listener) {
if (target.addEventListener) {
target.addEventListener(eventName, listener, false);
} else if (target.attachEvent) {
target.attachEvent("on" + eventName, listener);
}
}
// Start up library which allows saving of text selections
// This is useful for when you are doing anything that might destroy the original selection
rangy.init();
var editor = inputArea[0];
// Set up debounced event handlers
var editEvents = ["input", "keydown", "keypress", "keyup", "cut", "copy", "paste"];
for (var i = 0, eventName; eventName = editEvents[i++];) {
listen(editor, eventName, handleEditorChangeEvent);
}

immediateUpload / autoUpload with rich:fileupload

The upload doesnt start automatic when i choose a file. Still need to upload it manual by clicking the upload-button.
<rich:fileUpload ....
immediateUpload="true">
Is there a way to make this work?
Im using richfaces 4.2.1.
First copy the fileupload.js in to your application and add the same in your page like below:
<script type="text/javascript" src="#{facesContext.externalContext.requestContextPath}/js/fileupload.js"></script>
Second go to fileUpload.js and find a function called __updateButtons and update the first if which is checking the items length with the this.__startUpload();
like below.
__updateButtons: function() {
if (!this.loadableItem && this.list.children(".rf-fu-itm").size()) {
if (this.items.length) {
//this.uploadButton.css("display", "inline-block");
this.__startUpload();// New - Added the immediate upload to work.
} else {

Prevent onbeforeunload from being called when clicking on mailto link

Is there anyway to prevent onbeforeunload from being called when clicking on mailto link in chrome.
In FF, Safari, IE it is working fine.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript">
$(document).ready(function(){
window.onbeforeunload = confirmExit;
});
function confirmExit() {
return "Are you sure?";
}
</script>
</head>
<body>
Mail Link
</body>
</html>
What about a workaround?
$(document).ready(function(){
mailtoClicked = false;
window.onbeforeunload = confirmExit;
//Test if browser is Chrome
if (/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
$('a[href^=mailto]').click(function() {mailtoClicked = true;});
}
});
function confirmExit() {
if (!mailtoClicked) {
return "Are you sure?";
} else {
mailtoClicked = false;
}
}
Demo.
Here is a proposed solutions that looks reasonable
http://www.ilovebonnie.net/2009/09/23/how-to-use-onbeforeunload-with-form-submit-buttons/
UPDATE (link is dead) - Copied contents from Google Cache
How to Use onbeforeunload with Form Submit Buttons
September 23rd, 2009 — Geekery
While doing some programming I came across an interesting predicament. While I understand it’s evil to make it hard for a user to leave a page, I’m not here to argue the merits (or lack thereof) of onbeforeunload.
On a particular form, we are forcing the browser to not cache the information to avoid potential AJAX/JavaScript problems if they should leave the form and come back as browsers don’t all act the same (eg IE leaves checkboxes checked but doesn’t remember changes that have occurred to the page due to JavaScript). As such, we warn our users when they’re about to leave the order form to let them know they’ll need to fill it in again.
The function was simple enough:
window.onbeforeunload = function () {
return "You are about to leave this order form. You will lose any information...";
}
Unfortunately, this would also be triggered if the user submitted the form which, is obviously not what we want. After searching around on the Internet I came across a simple solution that I thought I would share:
// Create a variable that can be set upon form submission
var submitFormOkay = false;
window.onbeforeunload = function () {
if (!submitFormOkay) {
return "You are about to leave this order form. You will lose any information...";
}
}
Since onclick appears to register before onsubmit when clicking a submit button, we can add a little variable declaration to our submit button so that submitFormOkay will be set to true before the form submission happens:
<input type="submit" id="submit_button" onclick="submitFormOkay = true;">

yahoo autocomplete

I'm kind of like stuck trying to implement YUI autocomplete textbox. here's the code:
<div id="myAutoComplete">
<input id="myInput" type="text" />
<div id="myContainer"></div>
</div>
<script type="text/javascript">
YAHOO.example.BasicRemote = function() {
oDS = new YAHOO.util.XHRDataSource("../User/Home2.aspx");
// Set the responseType
oDS.responseType = YAHOO.util.XHRDataSource.TYPE_TEXT;
// Define the schema of the delimited results
oDS.responseSchema = {
recordDelim: "\n",
fieldDelim: "\t"
};
// Enable caching
oDS.maxCacheEntries = 5;
// Instantiate the AutoComplete
var oAC = new YAHOO.widget.AutoComplete("myInput", "myContainer", oDS);
oDS.generateRequest = function(sQuery) {
return "../User/Home2.aspx?method=" + "SA&Id="+document.getElementById("lbAttributes")[document.getElementById("lbAttributes").selectedIndex].value +"&query="+sQuery;
};
oAC.queryQuestionMark =false;
oAC.allowBrowserAutoComplete=false;
return {
oDS: oDS,
oAC: oAC
};
}
</script>
I've added all the yahoo javascript references and the style sheets but it never seems to make the ajax call when I change the text in the myInput box and neither does it show anything... I guess I'm missing something imp...
#Kriss -- Could you post a link to the page where you're having trouble? It's hard to debug XHR autocomplete without seeing what's coming back from the server and seeing the whole context of the page.
#Adam -- jQuery is excellent, yes, but YUI's widgets are all uniformly well-documented and uniformly licensed. That's a compelling source of differentiation today.
To be honest, and I know this isn't the most helpful answer... you should look into using jQuery these days as it has totally blown YUI out of the water in terms of ease-of-use, syntax and community following.
Then you could toddle onto http://plugins.jquery.com and find a whole bunch of cool autocomplete plugins with example code etc.
Hope this helps.

Resources